Question

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
Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top