Over a million developers have joined DZone.

Groovy: Picking a value from a number of options

· Java Zone

Discover how powerful static code analysis and ergonomic design make development not only productive but also an enjoyable experience, brought to you in partnership with JetBrains

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' :
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/

Learn more about Kotlin, a new programming language designed to solve problems that software developers face every day brought to you in partnership with JetBrains.


The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}