Search code examples
groovy

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


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.


Solution

  • 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