Kotlin: replace 'cascade if' with 'when' comparing with other variables
This should be the simplest equivalent of your if
expression:
var variable = when {
value < VAR_A -> valueA
value <= VAR_B -> valueB
value <= VAR_C -> valueC
else -> valueD
}
The ideal syntax you may be looking for is
when (value) {
< valueA -> valueA
<= valueB -> valueB
<= valueC -> valueC
else -> valueD
}
Unfortunately, this isn't possible because the comparison operators are operator overloads for functions requiring a receiver:
value < valueA
is the same as
value.compareTo(valueA) < 0
Because compareTo
is not a keyword like is
or in
(as used in zsmb13's answer), you would need to create this when
block:
when {
value < valueA -> valueA
value <= valueB -> valueB
value <= valueC -> valueC
else -> valueD
}
Kotlin is full of wonderful things. You could adventure into some alternative solutions that don't use a cascading conditional at all. It looks to me like you want value
to round up to the nearest of valueA
, valueB
, valueC
, and valueD
. So, for example, an alternative may be:
var variable = listOf(valueA, valueB, valueC, valueD).sorted().first { value <= it }
This will choose the closest value larger than value
from the set and assign it to variable
.