54

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

1
  • The same operator appears in some automatically generated Groovy scripts in Bonita Studio.
    – Olivier
    Commented Feb 13, 2020 at 14:44

2 Answers 2

80

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

3
  • 1
    I'm not familiar with Groovy, but how does other.is work if other is null?
    – chepner
    Commented Jun 12, 2014 at 14:10
  • 5
    Good Question. The implementation of is lies in DefaultGroovyMethods where the caller and callee is represented by param to this method and then checked for object reference equality, so there is no operation done on the caller.
    – dmahapatro
    Commented Jun 12, 2014 at 14:15
  • 4
    NPE = NullPointerException
    – StockB
    Commented Aug 23, 2017 at 16:04
17

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.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.