Kotlin when Expressions
Choose a result from several conditions with when.
Kotlin
fun grade(score: Int): String = when {
score >= 90 -> "A"
score >= 80 -> "B"
else -> "C"
}
fun main() {
println(grade(95))
println(grade(82))
println(grade(60))
}Output
A B C
Explanation
when is Kotlin's multi-way branch. Used without an argument, each branch is a Boolean condition, and the first one that is true supplies the result. else handles every remaining case.
when is an expression, so it produces a value and can be the body of a function with =. The compiler requires else in that case, because the expression must always have a result.
Explore the dry run
Guided walkthroughReady
1
fun grade(score: Int): String = when {2
score >= 90 -> "A"3
score >= 80 -> "B"4
else -> "C"5
}6
7
fun main() {8
println(grade(95))9
println(grade(82))10
println(grade(60))11
}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| The whole body is one when expression. | — | — | |
| 95 >= 90 is true, so the result is A. | score = 95 | A | |
| The first test fails; 82 >= 80 matches. | score = 82 | A B | |
| No test matches, so else gives C. | score = 60 | A B C |
Cost and common mistakes
O(1) time and space.
- Branches are checked top to bottom, so putting score >= 80 first would label 95 as B.
- A when used as an expression without else does not compile unless every case is covered.
Try it yourself
Add a D grade for scores of 70 or more.
Reveal answer and reasoning
Insert score >= 70 -> "D" before else. grade(60) still returns C.