Kotlin Enums
An enum class lists a fixed set of named values. Each value is one named choice from that set.
Printing an enum value
The value stored is Direction.NORTH. The print shows the name NORTH.
enum class Direction {
NORTH, SOUTH, EAST, WEST
}
fun main() {
val dir = Direction.NORTH
println(dir)
}A when that covers every value
Each branch matches one Direction value. Every value has a branch, so no else branch is needed.
enum class Direction {
NORTH, SOUTH, EAST, WEST
}
fun main() {
val dir = Direction.SOUTH
val label = when (dir) {
Direction.NORTH -> "Going north"
Direction.SOUTH -> "Going south"
Direction.EAST -> "Going east"
Direction.WEST -> "Going west"
}
println(label)
}An enum value with stored data
Each Level value stores a points number. The prints show the name first and the stored number second.
enum class Level(val points: Int) {
LOW(10), MEDIUM(20), HIGH(30)
}
fun main() {
println(Level.HIGH)
println(Level.HIGH.points)
}Example
enum class Level(val points: Int) {
LOW(10), MEDIUM(20), HIGH(30)
}
fun main() {
val level = Level.MEDIUM
val message = when (level) {
Level.LOW -> "Keep going"
Level.MEDIUM -> "Good progress"
Level.HIGH -> "Top level"
}
println("$message with ${level.points} points")
}Key points
- Enum class: a class that lists a fixed set of named values
- Use enum class to define a set of named choices
- Printing an enum value shows its name
- A when over an enum can cover every value
- A complete when over an enum needs no else branch
- An enum value can store extra data in a property
In this example, the level is MEDIUM. The when matches MEDIUM and gives the text Good progress. The print adds the stored points value 20 from the same enum value.
Note
Enum names are usually written in capital letters.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
What does printing an enum value show?