I am having trouble converting an if expression into a when expression in kotlin. My If code is as followed:
fun main() {
var cardPoints = 7_000
val cardLevel: String = if (cardPoints >= 0 && cardPoints < 1000) {
"pearl"
} else if (cardPoints >= 1000 && cardPoints < 5_000) {
"silver"
} else if (cardPoints >= 5_000 && cardPoints < 10_000) {
"gold"
} else {
"platinum"
}
val plural = if(cardPoints > 1 || cardPoints == 0) "s" else ""
println("You have $cardPoints point$plural and are at the $cardLevel level.")
}
However, I must now convert it into a "When" expression (preferably in ranges), this is what I have so far:
fun main() {
var cardPoints = 7_000
val cardLevel: String = when {
cardPoints >= 0 && cardPoints < 1000 -> "pearl"
cardPoints >= 1000 && cardPoints < 5_000 -> "silver"
cardPoints >= 5_000 && cardPoints < 10_000 -> "gold"
else -> "platinum"
}
val plural = if(cardPoints > 1 || cardPoints == 0) "s" else ""
println("You have $cardPoints point$plural and are at the $cardLevel level.")
}
I am unsure on what else needs to be tweaked or if I am missing something entirely. I would be thankful for any help and suggestions. Thanks.
if, press Alt+Enter and select "Replace if with when". This way has the benefit that it prevents errors that could potentially happen when manually converting code.