Instead of writing many if..else if expressions, you can use the when expression. It is much easier to read and allows you to test a variable against multiple values.
The when expression is similar to the switch statement in Java or C.
when Syntax
fun main() {
val day = 4
val result = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day."
}
println(result)
}
In this example:
when block evaluates the day variable.day (which is 4) with the case 4 -> "Thursday".result variable.else BranchThe else branch is executed if none of the other cases match. If you are using when as an expression (assigning it to a variable), the else branch is mandatory unless the compiler can prove all possible cases are covered.