Kotlin When
A when statement picks a branch by matching a value. The branch that matches runs its own code.
Matching single values
A branch is one choice inside the when braces. Each branch here holds one value, and the matching branch prints its line.
fun main() {
val day = 3
when (day) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
else -> println("Later")
}
}Several values in one branch
Commas let one branch hold two values. Either value runs the same branch.
fun main() {
val score = 2
when (score) {
1, 2 -> println("Low")
3 -> println("High")
else -> println("Other")
}
}Else as the fallback
No branch holds the stored value in this when. The else branch runs instead.
fun main() {
val grade = "X"
when (grade) {
"A" -> println("Top")
"B" -> println("Good")
else -> println("Ungraded")
}
}When gives a value
The when here is an expression, a piece of code that gives a value. The chosen word is stored and then printed.
fun main() {
val day = 2
val name = when (day) {
1 -> "Monday"
2 -> "Tuesday"
else -> "Later"
}
println(name)
}Example
fun main() {
val code = 2
when (code) {
1, 2 -> println("Start")
3 -> println("Middle")
else -> println("End")
}
val label = when (code) {
1, 2 -> "Early"
else -> "Late"
}
println(label)
}Key points
- Use when to pick a branch by matching a value.
- Each branch writes its value first, then an arrow, then its code.
- Write several values in one branch by separating them with commas.
- Use else for the branch that runs when no value matches.
- Only the matching branch runs.
- A when can give a value and store it in a val.
In this example, code holds 2. The first when matches the branch holding 1 and 2, so it prints Start. The second when matches the same branch and gives the word Early. The last print shows Early.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
A when matches the number 5 against branches holding 1 and 5, and an else branch. Which branch runs?