Instead of writing many if..else
expressions, you can use the when
expression, which is much easier to read.
It is used to select one of many code blocks to be executed:
Use the weekday number to calculate the weekday name:
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)
// Outputs "Thursday" (day 4)
Try it Yourself »
The when
expression is similar to the switch
statement in Java.
This is how it works:
when
variable (day) is evaluated onceelse
is used to specify some code to run if there is no matchday
is 4
, meaning "Thursday" will be printed截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!