-2

I have the following:

if (params.query?.equals(g.message(code: "layouts.main.search"))) {
  params.query = ""
}

What does the '?' part do?

Thomas Buckley
  • 5,836
  • 19
  • 62
  • 110
  • http://jlorenzen.blogspot.com.br/2007/10/using-groovy-to-easily-avoid-nasty.html –  Jan 22 '13 at 13:49
  • I'd love to know the reasoning for the downvote and by who? – Thomas Buckley Jan 22 '13 at 15:13
  • 1
    I downvoted. A simple google search answer this question, and there's also [duplicates](http://stackoverflow.com/questions/4581532/what-does-the-question-mark-mean-in-gsp-grails) of this in StackOverflow. –  Jan 22 '13 at 15:20
  • I thinks that's a bit harsh Sergio. Google my exact question title and see all top results come back with nothing, likewise for suggested questions/answers on SO. The question then becomes - maybe I could have thought of more approopriate terms to google search. For someone new to grails, it is not always easy to think of the appropriate termonology when performing searchs. 3 upvotes on the answer suggest people are landing here and finding it an appropriate question/answer. – Thomas Buckley Jan 24 '13 at 12:34
  • If I search with "grails question mark domain property", the first result in google is the duplicate that I pointed above. The 3 upvotes in the answer means that the answer is what you looking for, but in my opinion doesn't mean that's a good question. But it's just my opinion. –  Jan 24 '13 at 12:41

3 Answers3

3

It is a safeNavigation operator which returns nulls instead of throwing NullPointerExceptions.

Check the operators available in Groovy

http://docs.groovy-lang.org/latest/html/documentation/index.html#_safe_navigation_operator

Eel Lee
  • 3,513
  • 2
  • 31
  • 49
Raja Asthana
  • 2,080
  • 2
  • 19
  • 35
0

from groovy.org

Safe Navigation Operator (?.) The Safe Navigation operator is used to avoid a NullPointerException. Typically when you have a reference to an object you might need to verify that it is not null before accessing methods or properties of the object. To avoid this, the safe navigation operator will simply return null instead of throwing an exception, like so:

def user = User.find( "admin" )           //this might be null if 'admin' does not exist
def streetName = user?.address?.street    //streetName will be null if user or user.address is null - no NPE thrown
Dopele
  • 547
  • 3
  • 16
0

here the explantion for the ? operator:

http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator

in your case the ? operator protects the method call "equals" on a null object, e.g. the query param cannot be found in the parameter list.

hitty5
  • 1,653
  • 12
  • 25