Defining Enums
Named constant sets.
What Is an Enum?
An enum class defines a fixed set of named constants. Use it when a value can only be one of a small, known group of options.
- Each constant is an instance of the enum type.
- The compiler guarantees no other values are possible.
enum class Direction {
NORTH, SOUTH, EAST, WEST
}
fun main() {
val d = Direction.NORTH
println(d)
}Why Not Just Use Strings?
Strings allow typos and invalid values. An enum makes invalid states impossible: the compiler rejects anything outside the declared set.
enum class Status { ACTIVE, INACTIVE }
fun main() {
val s: Status = Status.ACTIVE
println("Current: $s")
}