when expression
- Kotlin course
- Beginner
- Lesson 40/116
- 5 min
Learn to use when as an expression.
The when expression
Like if, when can also be an expression that returns a value. For this, branches must produce values and else is required.
val day = 3
val name = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
else -> "Unknown"
}
println(name) // WednesdayEach branch's right side becomes a value; that value is assigned to name. day is 3, so "Wednesday" is chosen.
The expression form is ideal for storing the result in a variable or passing it to a method.
Practice Assign day name with a when expression
Write a fun main(). Assign 2 to val day. Write val name = when (day) { 1 -> "Monday" 2 -> "Tuesday" 3 -> "Wednesday" else -> "Unknown" }. Print the result with println(name).
Starter code
fun main() {
// Use a when expression
}Sample solution
fun main() {
val day = 2
val name = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
else -> "Unknown"
}
println(name)
}Expected output
Tuesday
Exhaustiveness
In a when expression, the compiler checks that all possible cases are covered. This is called exhaustiveness.
val status = when (code) {
200 -> "OK"
404 -> "Not found"
500 -> "Server error"
else -> "Unknown"
}Since code is an Int, listing all values is impossible, so else is required. But for binary types like Boolean, else is not needed.
If else is missing and a value falls through, you get a compile error.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the when forms
| Term | Meaning |
|---|---|
val n = when (x) { ... } |
Expression |
when (x) { println(...) } |
Statement |
1 -> "A" |
Value branch |
else -> "?" |
Default |
2 Complete the when branch
val name = when (day) {
1 -> "Monday"
____ -> "Tuesday"
else -> "Unknown"
}
val name = when (day) {
1 -> "Monday"
2 -> "Tuesday"
else -> "Unknown"
}
Explanation: 2 -> "Tuesday" matches the second day.
3 When is else required in a when expression?
- Never
- Only with two branches
- When the result is assigned to a value Correct answer
- Always required
Explanation: When when returns a value, else is required.