Exhaustive when
Cover all cases.
Covering All Cases
An exhaustive when handles every possible value. When used as an expression, Kotlin requires this so a result is always produced.
This lesson shows how to make when exhaustive and why it helps.
else Makes It Exhaustive
For open-ended subjects like Int, an else branch covers everything not listed.
This guarantees the when always matches.
fun label(n: Int): String = when (n) {
0 -> "zero"
1 -> "one"
else -> "many"
}
fun main() {
println(label(0))
println(label(5))
}All lessons in this course
- when as Expression
- Smart Casts
- is and as Operators
- Exhaustive when