Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "?:" operator used for in Groovy?

Tags:

Trying to understand this line of Groovy code:

return strat?.descriptor?.displayName ?: "null" 

Is the ?: a shorthand if/else? Does this mean if strat?.descriptor?.displayName is not null, print it, or else print null ?

I'm confused because there isn't anything between the ? and : like I would normally expect in an if/else statement.

like image 845
Taylor Patton Avatar asked Jan 04 '16 17:01

Taylor Patton


People also ask

What does operator mean in Groovy?

Groovy Programming Fundamentals for Java Developers An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Groovy has the following types of operators − Arithmetic operators. Relational operators.

How do I use not equal in Groovy?

In groovy, the ==~ operator (aka the "match" operator) is used for regular expression matching. != is just a plain old regular "not equals".

What is & symbol in Groovy script?

Groovy offers three logical operators for boolean expressions: && : logical "and" || : logical "or" ! : logical "not"


1 Answers

Just to add some more insight, the "?:" operator is known as the binary operator or commonly referred to as the elvis operator. The following code examples all produce the same results where x evaluates to true according to Groovy Truth

// These three code snippets mean the same thing.  // If x is true according to groovy truth return x else return y x ?: y  x ? x : y  // Standard ternary operator.  if (x) {   return x } else {   return y } 

Click here for more info on Elvis Operator

like image 81
dspano Avatar answered Sep 28 '22 09:09

dspano