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