Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of question mark(?) after a variable in Groovy

Tags:

groovy

People also ask

What does question mark do in Groovy?

Asking for help, clarification, or responding to other answers.

What is the usage of a question mark after a variable?

The question mark after the variable is called Optional chaining (?.) in JavaScript. The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null.

What is ?: In Groovy?

Yes, the "?:" operator will return the value to the left, if it is not null. Else, return the value to the right. "Yes, the "?:" operator will return the value to the left, if it is not null." - That is incorrect.


?. is a null safe operator which is used to avoid unexpected NPE.

if ( a?.b ) { .. }

is same as

if ( a != null && a.b ) { .. }

But in this case is() is already null safe, so you would not need it

other.is( this )

should be good.


There is a subtlety of ?., the Safe navigation operator, not mentioned in @dmahapatro's answer.

Let me give an example:

def T = [test: true]
def F = [test: false]
def N = null

assert T?.test == true
assert F?.test == false
assert N?.test == null // not false!

In other words, a?.b is the same as a != null && a.b only when testing for a boolean value. The difference is that the first one can either evaluate to a.b or null, while the second one can only be a.b or false. This matters if the value of the expression is passed on to another expression.