when Expression
Basic when Usage
when compares a subject value against a series of branches and executes the first one that matches, replacing long if/else if chains with clearer syntax.
Example: Basic when Usage
fun main() {
val day = 3
when (day) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
else -> println("Some other day")
}
}
Login to try C/C++/Java/PHP code in the editor
Matching Multiple Values
A single branch can match several values at once by separating them with commas, avoiding repeated branches for cases that should behave the same way.
Example: Matching Multiple Values
fun main() {
val letter = 'a'
when (letter) {
'a', 'e', 'i', 'o', 'u' -> println("Vowel")
else -> println("Consonant")
}
}
Login to try C/C++/Java/PHP code in the editor
Matching Ranges
Using in inside a when branch checks whether the value falls within a range, which is much clearer than several chained comparisons.
Example: Matching Ranges
fun main() {
val score = 85
when (score) {
in 90..100 -> println("Grade A")
in 80..89 -> println("Grade B")
in 70..79 -> println("Grade C")
else -> println("Grade F")
}
}
Login to try C/C++/Java/PHP code in the editor
when as an Expression
when can produce a value directly, with each branch's result becoming the overall value when that branch matches. An else branch is required unless the compiler can prove every case is covered.
Note: when { } with no subject lets each branch be its own boolean condition.
Example: when as an Expression
fun main() {
val number = 4
val description = when {
number % 2 == 0 -> "even"
else -> "odd"
}
println("$number is $description")
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting the
elsebranch when usingwhenas an expression on a type that is not exhaustive, causing a compile error. - Not realizing
whencan match ranges, multiple values, and even types, and instead writing a long chain ofif/else if. - Writing overlapping conditions in a
whenwithout an argument, not realizing only the first matching branch runs.
whencompares a value against several branches and runs (or evaluates to) the first one that matches.- A single branch can match multiple values separated by commas, or a range using
in. - When used as an expression,
whengenerally needs anelsebranch unless the compiler can prove all cases are covered (e.g. a sealed class or Boolean). whencan also be used with no argument at all, acting like a cleaner chain of conditions.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: