41

I saw this in my generated GSP pages. What does the ? mean?

<g:textField name="name" value="${phoneInstance?.name}" />
Ken Liu
  • 22,503
  • 19
  • 75
  • 98
Amir Raminfar
  • 33,777
  • 7
  • 93
  • 123

4 Answers4

62

It's the "Safe Navigation Operator", which is a Groovy feature that concisely avoids null pointer exceptions. See http://docs.groovy-lang.org/latest/html/documentation/index.html#_safe_navigation_operator

In this case, if phoneInstance is null, then it doesn't try to get the name property and cause a NPE - it just sets the value of the field tag to null.

Eel Lee
  • 3,513
  • 2
  • 31
  • 49
Burt Beckwith
  • 75,342
  • 5
  • 143
  • 156
  • Thank you! I had been googling it for a while but didn't find an answer. – Amir Raminfar Jan 03 '11 at 14:42
  • 11
    For extra coolness you can also add a sensible default with the Elvis operator eg: `${phoneInstance?.number?:'+44'}` Rock groovy with the king baby! – barrymac Jan 10 '12 at 16:15
4

The ? operator allows null values in Groovy (and thusly, GSP). For example, normally in gsp,

<g:field name="amount" value="${priceDetails.amount}" />

If priceDetails is null, this will throw a NullPointerException.

If we use the ? operator instead ...

<g:field name="amount" value="${priceDetails?.amount}" /> 

now the value of ${priceDetails?.amount} is null, instead of throwing a null pointer exception.

Kevin McCarpenter
  • 786
  • 1
  • 7
  • 22
1

This is very important feature in Groovy. If the object is null (ie, "phoneInstance" is null) then it's provide "null" value. This feature is called "Safe Navigation Operator". Simply when we use this feature , No need of checking the object("phoneInstance") is null or not.

Mohammed Shaheen MK
  • 1,199
  • 10
  • 10
1

the safe navigation operator (?.) returns null if the object on the left is null, otherwise it returns the value of the right member of that object. so phoneInstance?.name is just shorthandn for phoneInstance == null ? null : phoneInstance.name

for example:

a = x?.y

is just shorthand for:

a = (x == null ? null : x.y)

which is shorthand for:

if(x == null){
    a = null
} else {
    a = x.y
}
james turner
  • 2,773
  • 1
  • 21
  • 24