Does Groovy's ternary conditional operator support statements, not just expressions?
Asked Answered
L

2

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
Landgrabber answered 18/10, 2012 at 18:40 Comment(4)
that's not the elvis operator, thats a ternary conditional expressionHankow
it's also much more readable as you had it first with the if statements imo.Hankow
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 thatLandgrabber
no, I meant that using the ternary for this is going to look confusedHankow
J
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
Justen answered 18/10, 2012 at 20:32 Comment(0)
B
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).

Book answered 18/10, 2012 at 20:22 Comment(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, thxLandgrabber

© 2022 - 2024 — McMap. All rights reserved.