when as Expression
Return values from when.
when as an Expression
Kotlin's when is more than a switch statement. It is an expression, meaning it produces a value you can assign or return.
This makes branching logic concise and readable.
Returning a Value
When used as an expression, each branch supplies a result. The matching branch's value becomes the whole when result.
fun main() {
val day = 3
val name = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
else -> "Other"
}
println(name)
}All lessons in this course
- when as Expression
- Smart Casts
- is and as Operators
- Exhaustive when