All if-else
, if-else-if
& when
statements are expressions in Kotlin i.e. based on the condtion met, they represent a value. We can then store this value in variable. In the above rank example, we can make the code more concise like this :
var rankLabel = when (rank) {
1 -> "Winner"
2 -> "First Runner Up"
3 -> "Second Runner Up"
else -> "Participant"
}
Similarly, if-else
& if-else-if
statements are also expressions. We can re-write the above code using if-else-if
:
var rankLabel = if (rank == 1) {
"Winner"
} else if (rank == 2) {
"First Runner Up"
} else if (rank == 3) {
"Second Runner Up"
} else {
"Participant"
}