Kotlin when Expressions
Choose a result from several conditions with when.
On this page
Kotlin functions and comparison operators.
- Choose a result from several conditions with when.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
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))
}A B C
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
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))}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 |
Behind the scenes
How Kotlin processes this code
Kotlin commonly compiles to JVM bytecode, which the JVM executes.
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.