What is the purpose of question mark(?) after a variable in Groovy
I am new to grails I found in many examples that a variable may end with question mark (?) like this
boolean equals(other) {
if(other?.is(this))
return true
}
above code contains If condition in that other is ending with a ? so I want to know the meaning of that representation
?.
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.