Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the question mark mean in GSP/Grails?

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

<g:textField name="name" value="${phoneInstance?.name}" /> 
like image 206
Amir Raminfar Avatar asked Jan 03 '11 01:01

Amir Raminfar


People also ask

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.

What does question mark do in groovy?

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

How do I check for null objects in Groovy?

In Groovy we can do this shorthand by using the null safe operator (?.). If the variable before the question mark is null it will not proceed and actually returns null for you.

What is a GSP server?

Groovy Servers Pages (or GSP for short) is Grails' view technology. It is designed to be familiar for users of technologies such as ASP and JSP, but to be far more flexible and intuitive.


1 Answers

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.

like image 68
Burt Beckwith Avatar answered Oct 05 '22 11:10

Burt Beckwith