Using Kotlin WHEN clause for <, <=, >=, > comparisons -
i'm trying use when clause > or < comparison.
this doesn't compile. there way of using normal set of boolean operators (< <=, >= >) in comparison enable this?
val foo = 2 // doesn't compile when (foo) { > 0 -> dosomethingwhenpositive() 0 -> dosomethingwhenzero() < 0 -> dosomethingwhennegative() } i tried find unbounded range comparison, couldn't make work either? possible write unbounded range?
// trying unbounded range - doesn't compile when (foo) { in 1.. -> dosomethingwhenpositive() else -> dosomethingelse() } you can put whole expression in second part, ok seems unnecessary duplication. @ least compiles , works.
when { foo > 0 -> dosomethingwhenpositive() foo < 0 -> dosomethingwhennegative() else -> dosomethingwhenzero() } but i'm not sure simpler if-else alternative have been doing years. like:
if ( foo > 0 ) { dosomethingwhenpositive() } else if (foo < 0) { dosomethingwhennegative() } else { dosomethingwhenzero() } of course, real world problems more complex above, , when clause attractive doesn't work expect type of comparison.
even flexible language such kotlin doesn't have "elegant" / dry solution each , every case.
you can write like:
when (foo) { in 0 .. int.max_value -> dosomethingwhenpositive() 0 -> dosomethingwhenzero() else -> dosomethingwhennegative() } but depend on variable type.
i believe following form idiomatic in kotlin:
when { foo > 0 -> dosomethingwhenpositive() foo == 0 -> dosomethingwhenzero() else -> dosomethingwhennegative() } yeah... there (minimal) code duplication.
some languages (ruby?!) tried provide uber-elegant form case - there tradeoff: language becomes more complex , more difficult programmer know end-to-end.
my 2 cents...
Comments
Post a Comment