You know switch from other languages? Kotlin took that idea and made it way better with when. It's cleaner, more flexible, and it works as an expression too.
Basic when expression
Use when to match a value against multiple branches.
fun main() {
val day = 3
when (day) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
4 -> println("Thursday")
5 -> println("Friday")
else -> println("Weekend")
}
}
The arrow -> separates each branch from its action.
when with multiple values
You can match several values in one branch using a comma.
fun main() {
val grade = 'B'
when (grade) {
'A', 'B' -> println("Great job!")
'C' -> println("Not bad")
'D', 'F' -> println("Keep trying")
else -> println("Invalid grade")
}
}
Try it Yourself โ
when without an argument
Leave the argument out and when acts like a chain of if/else if โ perfect for complex conditions.
fun main() {
val x = 42
when {
x < 0 -> println("Negative")
x == 0 -> println("Zero")
x in 1..50 -> println("Between 1 and 50")
else -> println("Greater than 50")
}
}
The in keyword checks if a value falls within a range. More on that later.
when as an expression
Just like if, when can return a value. The last expression in each branch is the result.
fun main() {
val number = 2
val text = when (number) {
1 -> "One"
2 -> "Two"
3 -> "Three"
else -> "Unknown"
}
println(text)
}
When used as an expression, else is required unless the compiler can prove all cases are covered.