0Pricing
Kotlin Academy · Lesson

Enums with when

Exhaustive handling.

Enums Pair Well with when

The when expression is the natural way to branch on an enum. Each constant gets its own branch.

enum class Light { RED, YELLOW, GREEN }

fun action(l: Light) = when (l) {
    Light.RED -> "Stop"
    Light.YELLOW -> "Slow"
    Light.GREEN -> "Go"
}

fun main() {
    println(action(Light.GREEN))
}

Exhaustiveness

When when is used as an expression on an enum and covers every constant, no else branch is needed. The compiler verifies completeness.

enum class Coin { HEADS, TAILS }

fun flip(c: Coin) = when (c) {
    Coin.HEADS -> "Win"
    Coin.TAILS -> "Lose"
}

fun main() {
    println(flip(Coin.HEADS))
}

All lessons in this course

  1. Defining Enums
  2. Enum Properties and Methods
  3. Enums with when
  4. Enum Values and Ordinals
← Back to Kotlin Academy