The when expression in Kotlin is a powerful alternative to the traditional if-else-if ladder. It is used to:
if-else statements.
The when expression evaluates a value or condition and executes the corresponding block.
fun main() {
val day = 3
val dayName = when(day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day"
}
println("Day: $dayName")
}
Output:
Day: Wednesday
Matches a value against constants:
val color = "Red"
when (color) {
"Red" -> println("Stop")
"Green" -> println("Go")
"Yellow" -> println("Caution")
else -> println("Unknown color")
}
You can group multiple conditions with commas:
val number = 3
when (number) {
1, 3, 5, 7, 9 -> println("Odd number")
2, 4, 6, 8, 10 -> println("Even number")
else -> println("Out of range")
}
When can return a value:
val score = 85
val grade = when {
score >= 90 -> "A"
score >= 75 -> "B"
score >= 60 -> "C"
else -> "Fail"
}
println("Grade: $grade")
You can check for ranges or types:
val x: Any = 42
when (x) {
in 1..50 -> println("x is between 1 and 50")
is String -> println("x is a string")
else -> println("Unknown type or value")
}
if-else-if chains.else branch is optional if all possible values are covered.when expression instead of multiple if-else statements?