The when expression is a switch-case in other languages like JavaScript but more powerful than the latter.
When a when statement is used as an expression, the compiler will require that the when statement is exhaustive, covering all possible input.
val race = "Hylian"
val popularCharacter = when (race) {
// this is using the `==` operator for comparison
"Hylian", "Human" -> "Link"
"Sheikah" -> "Impa"
"Zora" -> "Ruto"
else -> {
// This `else` branch adds a fallback option to satisfy
// the compiler regarding the exhaustive behavior of `when`
"Tingle"
}
}When expressions with variable declarations
Sometimes, we will use a when expression with an argument that we compute only for the sake of using it inside the when expression.
val playerLevel = experience/100 + 1
val playerTitle = when (playerLevel) {
1 -> "Noob"
in 2..10 -> "Level $playerLevel Chad"
else -> "Doge Knight"
}The previous code can be refactored like this, making the playerLevel variable scoped only inside the when statement.
val playerTitle = when (val playerLevel = experience/100 + 1) {
// ...
}When expressions without arguments
A when statement without an argument is an interchangeable if/else statement
val status = when {
experience > requiredExperience -> "Get more experience!"
experience == requiredExperience -> "You can level up!"
requiredExperience - experience < 25 -> {
"You're almost there, keep getting experience"
}
}