Careeroza
Enums with when
Exhaustive when
When when is used as an expression on an enum, it must cover every constant (or have else). If you later add a new constant, the compiler shows an error everywhere it is not handled - a big safety win.
Example
enum class TrafficLight { RED, YELLOW, GREEN }
fun action(light: TrafficLight): String = when (light) {
TrafficLight.RED -> "Stop"
TrafficLight.YELLOW -> "Get ready"
TrafficLight.GREEN -> "Go"
// no else needed: all cases are covered
}
fun main() {
TrafficLight.entries.forEach { println("$it -> ${action(it)}") }
}Output
RED -> Stop YELLOW -> Get ready GREEN -> Go
Tip: Avoid else in a when over an enum or sealed type. Without else, the compiler reminds you to handle new values.
Exercise
Exercise: Create enum class Day with the 7 days and a function isWeekend() written with when. Print the weekend days.
Show answer
enum class Day {
MON, TUE, WED, THU, FRI, SAT, SUN;
fun isWeekend() = when (this) {
SAT, SUN -> true
else -> false
}
}
fun main() {
println(Day.entries.filter { it.isWeekend() }) // [SAT, SUN]
}