Enum Class (Kotlin)
An enum class defines a fixed set of named constants. Kotlin enums can carry properties, implement interfaces, and have methods, while still working seamlessly in exhaustive when expressions.
Kotlin
enum class Direction { NORTH, SOUTH, EAST, WEST } creates four singleton instances. Each constant has an ordinal (position) and name, and you can iterate all of them with values() / entries or look one up by name with valueOf().
Kotlin enums are more than labels: you can give the enum a constructor and attach data to each constant (RED(0xFF0000)), define methods, and even override behavior per constant. They can also implement interfaces.
In a when, handling every enum constant makes the when exhaustive with no else, and adding a new constant later flags those when blocks. For variants that hold different shapes of data, prefer a sealed class instead.
Syntax
enum class Status(val code: Int) {
OK(200), NOT_FOUND(404)
}Examples
Kotlin
enum class Status(val code: Int) {
OK(200),
NOT_FOUND(404)
}
val s = Status.NOT_FOUND
println("${s.name} ${s.code}")Output:
NOT_FOUND 404