I'm trying to use the WHEN
clause with a >
or <
comparison.
This doesn't compile. Is there a way of using the normal set of boolean operators (< <=, >= >) in a comparison to enable this?
val foo = 2
// doesn't compile
when (foo) {
> 0 -> doSomethingWhenPositive()
0 -> doSomethingWhenZero()
< 0 -> doSomethingWhenNegative()
}
I tried to find an unbounded range comparison, but couldn't make this work either? Is it possible to write this as an unbounded range?
// trying to get an unbounded range - doesn't compile
when (foo) {
in 1.. -> doSomethingWhenPositive()
else -> doSomethingElse()
}
You can put the whole expression in the second part, which is OK but seems like unnecessary duplication. At least it compiles and works.
when {
foo > 0 -> doSomethingWhenPositive()
foo < 0 -> doSomethingWhenNegative()
else -> doSomethingWhenZero()
}
But I'm not sure that is any simpler than the if-else alternative we have been doing for years. Something like:
if ( foo > 0 ) {
doSomethingWhenPositive()
}
else if (foo < 0) {
doSomethingWhenNegative()
}
else {
doSomethingWhenZero()
}
Of course, real world problems are more complex than the above, and the WHEN
clause is attractive but doesn't work as I expect for this type of comparison.
question from:
https://stackoverflow.com/questions/45377386/using-kotlin-when-clause-for-comparisons 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…