when with enum
- Kotlin course
- Beginner
- Lesson 97/116
- 5 min
Learn branching on enums with when.
when with enum: exhaustive branches
When you list every constant of an enum in a when, no else is needed. If you add a new constant, the compiler demands a new branch; the error is caught early.
fun describe(c: Color) = when (c) {
Color.RED -> "red"
Color.GREEN -> "green"
Color.BLUE -> "blue"
}This is called an exhaustive when; every constant is written out. If you forget one, the compiler warns you. Adding a new constant is safe; every branch gets reviewed.
Exhaustion and new constants
If you add a new constant to an enum with an exhaustive when, the compiler warns you. This means adding a constant is safe.
enum class Color { RED, GREEN, BLUE }
// adding YELLOW breaks describe
// a new branch covering it is requiredWhen you see the warning you add a branch; no constant slips through. This prevents future breakage. Writing every constant explicitly is safer than an else.
Practice Describe directions
Define an enum class called Direction with NORTH, SOUTH, EAST, WEST. Write fun describe(d: Direction): String giving each direction a word with when. In main print describe(Direction.NORTH).
Starter code
fun main() {
// Define a direction type; print a direction name via describe
}Sample solution
enum class Direction { NORTH, SOUTH, EAST, WEST }
fun describe(d: Direction) = when (d) {
Direction.NORTH -> "north"
Direction.SOUTH -> "south"
Direction.EAST -> "east"
Direction.WEST -> "west"
}
fun main() {
println(describe(Direction.NORTH))
}Expected output
kuzey
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 If a when lists every enum constant, what is not needed?
- No else branch needed Correct answer
- It needs a loop
- It only runs one branch
- It changes constants
Explanation: Listing all constants means no else; the compiler enforces it.
2 Fill in the blank: add a when branch
when (c) {
Color.RED -> "red"
____ -> "green"
}
when (c) {
Color.RED -> "red"
Color.GREEN -> "green"
}
Explanation: you added a branch for Color.GREEN.
3 Match constant to text
| Term | Meaning |
|---|---|
Color.RED |
red |
Color.GREEN |
green |
Color.BLUE |
blue |