when Expression (Kotlin)

when is Kotlin's multi-branch conditional, replacing switch. It can match values, ranges, types, or arbitrary boolean conditions, and it's an expression that returns a value.

Kotlin

when checks a subject against a series of branches and runs the first that matches: literals, multiple comma-separated values, in ranges, is type checks, or a bare else. Unlike Java's switch there's no fall-through, so no break is needed.

Used as an expression (val x = when(...)), it must be exhaustive — cover every case or include an else. With sealed classes and enums the compiler knows all the cases, so it can verify exhaustiveness without else, which is a key pattern in idiomatic Kotlin.

A subject-less form, when { condition1 -> ...; condition2 -> ... }, acts like a clean if/else if chain. Combined with is checks, when also enables smart casts inside each branch.

Syntax

when (x) {
    1 -> "one"
    2, 3 -> "few"
    in 4..10 -> "several"
    else -> "many"
}

Examples

Kotlin

fun describe(x: Int): String = when (x) {
    0 -> "zero"
    in 1..9 -> "small"
    else -> "big"
}
println(describe(5))
println(describe(100))

Output:

small
big

Learn it in a lesson

See also

Back to the Dictionary