Evgeny Goldin works as a Technical Evangelist for the JetBrains TeamCity CI build server. He speaks Java, JavaScript, Perl and Groovy. His favorite products are MediaWiki, Intellij IDEA, Git, Artifactory, Gradle, YouTrack and TeamCity. He enjoys driving, learning and solving challenging problems. He doesn't like wasting time and being unproductive and believes that simplicity, attention to details and tidy working environments are the most efficient approaches to successful delivery. Evgeny is a DZone MVB and is not an employee of DZone and has posted 17 posts at DZone. You can read more from them at their website. View Full User Profile

Groovy: Picking a value from a number of options

03.28.2011
| 5562 views |
  • submit to reddit

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" )

 

From http://evgeny-goldin.com/blog/picking-value/

Published at DZone with permission of Evgeny Goldin, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Vijay Nathani replied on Mon, 2011/03/28 - 1:52am

In groovy, we can also do
def a = 2
def searchValue  = { [1:'aa', 2:'bb', 3:'cc'].get(it,'dd') }
def x = searchValue(a)
Vijay.

Bungle Feet replied on Mon, 2011/03/28 - 7:22am in response to: Vijay Nathani

Or:

def a = 2

def x = ({[1:'aa',2:'bb',3'cc'][it]?:'dd'})(a)

Saving a few keystrokes ;)  (and assuming the vals are always truthy!)

 Bungle

Evgeny Goldin replied on Mon, 2011/03/28 - 8:00am

Nice, thanks guys! Added a link back to those comments in the original post.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.