Part 04 / Topic 2 of 8
when with a subject: statement and expression
when (subject) { ... } compares one value against several branches, top to bottom, and runs the
first match — the Kotlin shape of what Java/C call switch, with no fallthrough and no break needed.
Like if, it works as a statement or as an expression.
val day = 3
// statement form
when (day) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
else -> println("Some other day")
}
// expression form: every branch must produce a value, and every possible input must be covered
val dayName = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6, 7 -> "Weekend" // comma combines branches -- still exactly one match, no fallthrough
else -> "Invalid day"
}
println("Day name: $dayName")
Wednesday
Day name: Wednesday
A branch can also be a range check instead of one exact value, using in:
val km = 12
val fare = when (km) {
in 0..5 -> 20
in 6..15 -> 35
in 16..30 -> 60
else -> 100
}
println("Auto fare for $km km: ₹$fare")
Auto fare for 12 km: ₹35
Real-world example: an auto-rickshaw fare slab, a shipping-weight band, an exam grade band — any
time a value falls into one of several labelled ranges, a when with in branches reads far more
directly than a stack of if (x in a..b) checks.
The subject itself can be declared right inside the parentheses, scoped to the when alone:
val autoFare = when (val distance = 18) {
in 0..5 -> 20
in 6..15 -> 35
else -> {
println("Distance $distance km is outside the short-trip bands")
60
}
}
println("Fare: ₹$autoFare")
Distance 18 km is outside the short-trip bands
Fare: ₹60
distance only exists inside this when — useful when the subject itself is a small computation
you don't need anywhere else.
🔍 Going deeper: as an expression,
whenmust be exhaustive — every possible input must be covered. Dropping theelseabove a non-exhaustive subject type (a plainInt, here) fails to compile:error: 'when' expression must be exhaustive. Add an 'else' branch.Parts 9's
sealed class/enumwhenis the one case whereelsecan be dropped safely — the compiler already knows every possible subtype, and will flag a new one you forgot to handle. A plainInt,StringorBooleansubject has no such closed set, soelseis how you spell "everything else."
Full program: examples/02_when_with_subject.kt.
Done here? The practice set for Part 4 — including the solutions — is on the part page.