Skip to the workspace
Pebellslearn by building
Conditional Expressions and Loops  ›  Lesson

when Expressions

when 15 minwhen compares a value against a list of branches, taking the first match with no fall-through, and can match constants, ranges, types or free-standing conditions.

kotlin / when Expressions

Explore each scene at your own pace.

01 · The rule

The rule

when Expressions

when compares a value against a list of branches, taking the first match with no fall-through, and can match constants, ranges, types or free-standing conditions.

Match alternative cases and make the fallback or exhaustiveness requirement explicit.

The café sells three cup sizes, four drink types and a happy-hour price between 15 and 17. A tower of else if lines works, but it buries the choices. when lays them out like a menu board: one line per case.

The rule

when picks the first matching branch; as a value, cover every case.

val price = when (size) {
    'S' -> 2.5
    'M' -> 3.0
    'L' -> 3.5
    else -> 0.0
}

when (size) compares size against each branch from top to bottom. The first match runs, and only that one: there is no fall-through, so no break is needed.

Branches can test much more than equality:

val note = when (hour) {
    8, 9 -> "Morning rush"          // several values, comma-separated
    in 15..16 -> "Happy hour"       // a range
    !in 8..17 -> "Closed"           // outside a range
    else -> "Regular service"
}

fun describe(item: Any) = when (item) {
    is String -> "Drink: $item"     // a type check, with smart cast
    is Int -> "Cups: $item"
    else -> "Unknown"
}

Without a subject, when replaces an if-else if chain, each branch being any Boolean condition:

val label = when {
    visits >= 10 -> "regular"
    visits >= 3 -> "returning"
    else -> "new"
}

Exhaustiveness. When when produces a value, every possible input must be covered. For open types like Int, Char or String, that means an else. For a Boolean (both true and false listed) or an enum or sealed type with every case listed, the compiler can prove coverage and else is optional.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.