5

Is it possible to include statements with expressions with Groovy's conditional operator? This is what I'm doing now, and I want break this down in a single conditional statement with the println statements...

if(!expired){
  println 'expired is null'
  return true
}
else if( now.after(expired)){
  println 'cache has expired'
  return true
}
else
  return false

Converted into single statement...

return (!expired) ? true : (now.after(expired)) ? true : false

...would like to do something like this for debugging purposes...

return (!expired) ? println 'expired is null' true : (now.after(expired)) ? println 'cache has expired' true : false
4
  • 3
    that's not the elvis operator, thats a ternary conditional expression
    – tim_yates
    Oct 18, 2012 at 18:51
  • 1
    it's also much more readable as you had it first with the if statements imo.
    – tim_yates
    Oct 18, 2012 at 18:52
  • Are you implying that it's possible to mix statements and expressions, despite it being more readable with if/else statements? curious to see an example of that
    – raffian
    Oct 18, 2012 at 19:43
  • 2
    no, I meant that using the ternary for this is going to look confused
    – tim_yates
    Oct 18, 2012 at 20:55

2 Answers 2

9

As GrailsGuy said in the other answer, use closures:

def expired= false, expired2= true
return (!expired) ? 
  {println "expired is null"; true}() :
  (expired2) ? {println "cache has expired"; true}() : false
0
4

I believe the Groovy ternary operator behaves the same as the Java one, and therefore only allows expressions.

The way you have it now is not legal at all:

println 'expired is null' true

The issue is that it expects a semicolon or new line, and does not receive one.

Changing it to this:

println 'expired is null'; return true;

does not work either, which supports the fact that it only allows expressions. If you really want to use the ternary operator and execute multiple lines, then you are best off putting that logic in a method (or closure).

1
  • 1
    I thought Groovy had a cool way of doing ti, I'm always finding new stuff in Groovy that never ceases to amaze me, thx
    – raffian
    Oct 18, 2012 at 20:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.