Sobes.tech
Middle

What are the features of working with Enum classes in Kotlin?

sobes.tech AI

Answer from AI

An enum class is a special type of class used to represent a set of constants.

Features:

  • Defining constants: Each constant in the enumeration is an instance of the enum class.
enum class Color {
    RED, GREEN, BLUE
}
  • Properties and methods: Enum classes can have properties and methods. Each constant can implement them differently.
enum class Status(val description: String) {
    SUCCESS("Operation completed successfully"),
    ERROR("An error occurred"),
    PENDING("Waiting")
}

enum class Direction {
    NORTH, SOUTH, EAST, WEST;

    fun getOpposite(): Direction {
        return when (this) {
            NORTH -> SOUTH
            SOUTH -> NORTH
            EAST -> WEST
            WEST -> EAST
        }
    }
}
  • Anonymous classes: Each enum constant can be declared with an anonymous class providing its own implementations of methods or properties.
enum class State {
    IDLE {
        override fun signal() = READY
    },
    READY {
        override fun signal() = IDLE
    }; // Semicolon is mandatory before declaring class members

    abstract fun signal(): State
}
  • Implementing interfaces: Enum classes can implement interfaces.
interface Printable {
    fun printName()
}

enum class Shape : Printable {
    CIRCLE {
        override fun printName() {
            println("Circle")
        }
    },
    SQUARE {
        override fun printName() {
            println("Square")
        }
    }
}
  • Built-in properties: Each constant has built-in properties name (the name of the constant as a string) and ordinal (the position of the constant in the declaration, starting from 0).
enum class Priority {
    LOW, MEDIUM, HIGH
}

fun main() {
    println(Priority.MEDIUM.name)    // Output: MEDIUM
    println(Priority.HIGH.ordinal) // Output: 2
}
  • Built-in functions:
    • enumValues<T>(): Returns an array of all constants in the enum class.
    • enumValueOf<T>(name: String): Returns the enum constant with the specified name. Throws IllegalArgumentException if not found.
fun main() {
    val allPriorities = enumValues<Priority>()
    println(allPriorities.joinToString()) // Output: LOW, MEDIUM, HIGH

    val highPriority = enumValueOf<Priority>("HIGH")
    println(highPriority) // Output: HIGH
}
  • Using in when expressions: Ideal for use in when. The compiler will warn if not all branches are covered (when used as an expression with a return value).
fun processStatus(status: Status) {
    when (status) {
        Status.SUCCESS -> println("Success")
        Status.ERROR -> println("Error")
        Status.PENDING -> println("Waiting")
    }
}

Enums in Kotlin are more powerful compared to their counterparts in Java, allowing adding properties, methods, and implementing interfaces.