when
- Kotlin course
- Beginner
- Lesson 39/116
- 5 min
Learn multi-way selection with when.
The when statement
when compares a value against several possible cases. It is like Java's switch but more powerful. Each branch uses ->.
val day = 3
when (day) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
else -> println("Unknown")
}day is 3, so the 3 -> branch runs and prints "Wednesday". If no branch matches, the else branch runs.
when is more readable; it replaces long if/else if chains.
Practice Convert day number to name
Write a fun main(). Assign 3 to val day. Use when (day) to print the day name: 1 "Monday", 2 "Tuesday", 3 "Wednesday", else "Unknown".
Starter code
fun main() {
// Convert day number to name
}Sample solution
fun main() {
val day = 3
when (day) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
else -> println("Unknown")
}
}Expected output
Wednesday
Multiple values and ranges in when
when branches can list several values with commas or use ranges with in.
val n = 5
when (n) {
1, 2, 3 -> println("Small")
in 4..7 -> println("Medium")
else -> println("Large")
}n is 5, so the in 4..7 branch runs and prints "Medium". Ranges use ..; you'll see them in detail later.
If no branch matches, else runs. else is optional, but with no match nothing runs.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does when (day) { ... } compare against?
- A fixed value
- The day variable Correct answer
- A Boolean
- A random value
Explanation: when (day) compares day's value against the branches.
2 Complete the when branch
when (day) {
1 -> println("Monday")
2 -> println("Tuesday")
____ -> println("Wednesday")
}
when (day) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
}
Explanation: 3 -> println("Wednesday") matches the third day.
3 Match the when forms
| Term | Meaning |
|---|---|
1 -> ... |
Single value branch |
1, 2 -> ... |
Multi value branch |
in 4..7 -> ... |
Range branch |
else -> ... |
Default branch |