0Pricing
Kotlin Academy · Lesson

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

  1. when as Expression
  2. Smart Casts
  3. is and as Operators
  4. Exhaustive when
← Back to Kotlin Academy