0

I am new with groovy/grails. Want to ask what is the difference between:

String x = params?.var1

and

String x=params.var1

Why do we use that "?" in controller?

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
  • 3
    Possible duplicate of [What does the question mark operator mean in Ruby?](https://stackoverflow.com/questions/1345843/what-does-the-question-mark-operator-mean-in-ruby) – moritzg Jul 27 '17 at 08:20

1 Answers1

0

? is called Safe Navifation operator in Groovy. It means that it will silently catch NullPointerException if it happens and return null instead. For example:

Map params = null
String x = params?.var1 // assigns null to variable x
String y = params.var1 // throws NullPointerException because params is null

It's pretty useful if you assume that specific variable may be a null and you don't want to check if it's not null every time. In this case you use safe navigation operator instead and you accept that the result of chained calls may return null.

Reference: http://groovy-lang.org/operators.html#_safe_navigation_operator

Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131