when Expressions
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.
The shortcut
Scan the branches top to bottom and stop at the first hit. When writing one, put specific cases first and broad ones last, and finish with else unless the compiler can see that every case is covered.
Branch 1
8, 9— 9 is in the list. Match.
Drills
Answer fast — trust the rule.
How many branches run in a when when two of them match?
Which branch condition matches any hour from 12 to 14 inclusive?
val x = when (n) { 1 -> "one"; 2 -> "two" } with n: Int. What happens?
What does when { cups > 10 -> "A"; cups > 5 -> "B"; else -> "C" } give for cups = 12?
Remember
whenruns only the first matching branch; there is no fall-through.- Branches can match values, lists, ranges (
in) and types (is). - As a value it must be exhaustive: add
elseunless every case is listed.
