Groovy Elvis Operator

What is this Elvis Operator I vaguely recall? I’ll get to that just bear with me for a minute.
In Java I’ve seen too many null checks like the following:

If (something != null) {
    val = something 
} else { 
    val = defaultValue 

Its handy to have the Groovy Truth so we don’t have to do null checks.

Instead of writing if (something != null) { … } we write if (something) { … }

Well this type of branching logic is precisely why we have the ternary operator in both Java and Groovy.
I’m surprised that the ternary operator is neglected by many developers.
It turns our 4 lines of if/else logic into a single line like:

 val = something ? something : defaultValue 

The syntax and logic for the ternary operator is the same in Groovy as it is in Java;

(Condition) ? Value-If-True : Value-If-False

I’m not going to get into a lesson on the ternary operator and you can certainly read more here.
When using the ternary operator, I had to repeat the variable something twice to do a simple check; This isn’t groovy and it definitely doesn’t lend itself to the principles of DRY! *Queue the Elvis operator*
Instead of writing:

 val = something ? something : defaultValue 

We write:

 val = something ?: defaultValue 

A more clear example would be as follows:

def rockstar
def defaultrockstar = rockstar ?: "Elvis Presley"
assert defaultrockstar == "Elvis Presley"

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s