Enum Classes
Prerequisites: The when expression, Classes and objects
An enum class defines a type with a fixed set of possible values. Use one whenever a value must be one of a known list of options.
Example
enum class Direction { NORTH, SOUTH, EAST, WEST }
fun arrow(d: Direction) = when (d) {
Direction.NORTH -> "↑"
Direction.SOUTH -> "↓"
Direction.EAST -> "→"
Direction.WEST -> "←"
}
fun main() {
val heading = Direction.EAST
println(heading)
println(arrow(heading))
println(heading.ordinal)
println(Direction.valueOf("WEST"))
println(Direction.entries)
}
Expected output
EAST
→
2
WEST
[NORTH, SOUTH, EAST, WEST]
- The
whenneeds noelse: it covers every value. If you add a new direction later, the compiler reports everywhenthat doesn't handle it. ordinalis the position (from 0);nameis the text.valueOf("WEST")converts text to an enum value (and throws for unknown text).entrieslists every value, in order.
Properties and methods
Enum values can carry data, and enums can have methods:
enum class Size(val ml: Int, val price: Double) {
SMALL(250, 2.5),
MEDIUM(350, 3.0),
LARGE(450, 3.5);
fun label() = "${name.lowercase()} (${ml}ml): $$price"
}
fun main() {
for (size in Size.entries) {
println(size.label())
}
}
small (250ml): $2.5
medium (350ml): $3.0
large (450ml): $3.5
Note the semicolon after the last value — it's required when the enum has a body with members.
Common mistakes
- Using strings like
"small"for a fixed set of options. A typo in a string is a silent bug; a typo in an enum value is a compile error. - Adding an
elsebranch to awhenover your own enum. It hides the compile error you'd otherwise get when a new value is added.