Groovy Ternary Operator

Another one of the great operators that more and more languages support is their ternary operator. The ternary is a conditional operator and often referred to as an inline if statement. Before we look at how to use it lets take a look at a common problem it helps us solve. There are often times when you want to set a variable to one value if an expression evaluates to true and another if its false. In pseudo code it might look something like this.

If expression is true; set value to a else set value to b

Say we are displaying the weather to a user. We know the users state because we require it in our application but maybe they haven’t told us exactly what city they live in. In the following examples (ColdFusion & Groovy) we check to see if the city is null. If it is we set the location to the state and if it is not we will use that.

This is fine but its a lot of excess noise that we don’t need. Both ColdFusion and Groovy support the ternary operator and I won’t show it in both because its pretty easy to understand. If the expression before the ? evaluates to true state will be used and if it evaluates to false (we have a city) then city will be used.

Groovy actually takes this one step further though . Most of the time we are doing checks like the one above. We have one value that we want to use (a default) but if it doesn’t exist use another. In Groovy we can represent that default using ?:

Hi, I’m Dan Vega. I am a Software Engineer living just outside of one of my favorite places in the world, Cleveland Ohio. I am a self-taught programmer who firmly believes that you can accomplish anything in this life if you put your mind to it, roll up your sleeves and are willing to put in the work.

I have been writing software for over 16+ years now and I use my knowledge, passion, and influence to help other developers achieve their goals. I teach online and currently, have over 19,000 students.

When I am not writing software I have a number of things that really keep me busy. I love to read books, listen to podcasts and watch online courses. I have a real thirst for knowledge and it consumes me every single day of the week. I also love to run & lift heavy weights which keep me balanced throughout the week.

Please note: I reserve the right to delete comments that are offensive or off-topic.

  • Railo also supports the Elvis operator as it’s called– ?:

    FWIW, I also added a Railo ticket recently inspired by how languages like Groovy handle truth which would make CFML’s ternary null check as simple as Groovy’s.

  • Thanks Brad. The null safe operator is pretty awesome, i’m enjoying learning the ins and outs of a new language. It’s definitely brought some perspective.