Groovy: Picking a value from a number of options
Let’s say you need to define a value based on a number of conditions. If first condition holds true, then the value is X, if second condition holds true then the value is Y and so on. I used to go with a multi-level ternary operator to accomplish that:
def a = 2
def x = ( a == 1 ) ? 'aa' :
( a == 2 ) ? 'bb' :
( a == 3 ) ? 'cc' :
'dd'
assert x == 'bb'
Today @tim_yates has suggested a more debuggable way:
def a = 2
def x = a.with { switch( it ) {
case 1 : return 'aa'
case 2 : return 'bb'
case 3 : return 'cc'
default : return 'dd' }
}
assert x == 'bb'
Thanks, Tim! Will start using it now. This is very close to Scala version, which is even shorter:
val a = 2
val x = a match {
case 1 => "aa"
case 2 => "bb"
case 3 => "cc"
case _ => "dd"
}
assert ( x == "bb" )
Searching YouTrack with Chrome keyword search Taking notes: Google, Zoho, OneNote, Evernote


In case the conditions only check for a value being in one of multiple adjacent ranges, Python’s `bisect` module comes in very handy:
>>> from bisect import bisect_left
>>> def grade(score, thresholds=[60, 70, 80, 90], grades=’FDCBA’):
… index = bisect_left(thresholds, score)
… return grades[index]
…
>>> map(grade, [33, 99, 77, 70, 89, 90, 91, 100])
['F', 'A', 'C', 'D', 'B', 'B', 'A', 'A']
For readable formatting, see: http://paste.pocoo.org/show/361372/
For the module documentation and the example’s origin, see: http://docs.python.org/library/bisect.html#module-bisect
Unfortunately, I haven’t found something like this other languages/language ecosystems. If anyone knows of such a thing in e.g. Scala or Java, please enlighten me.
You can do this in Groovy http://paste.pocoo.org/show/EedpgDUCdRobyuY9eoF3/ Though admittedly, that just reproduces your example, and not the functionality of bisect
Some more neat examples were posted on DZone: http://java.dzone.com/articles/groovy-picking-value-number