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

Groovy

Groovy Problem Overview


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

Groovy Solutions


Solution 1 - Groovy

?. 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.

Solution 2 - Groovy

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3301669View Question on Stackoverflow
Solution 1 - GroovydmahapatroView Answer on Stackoverflow
Solution 2 - GroovyjacwahView Answer on Stackoverflow