Tuesday, September 9, 2008

Safe dereferencing with the ?. operator

  When a reference doesn’t point to any specific object, its value is null. When calling a method or accessing a field on a null reference, a NullPointerException (NPE) is thrown. This is useful to protect code from working on undefined preconditions,but it can easily get in the way of “best effort” code that should be executed for valid references and just be silent otherwise.that is the "?." operator in Groovy.for example 
def map=[x:[y:[z:1]]]
assert map.x.y.z==1
assert map.x.a==null//it'll throw an null exception ,because there isn't a "a" attribute.
try{
assert map.x.a==null
}catch(Exception){
 //some code for process exception.
}
//this method is better,but it's a bit verbose.right?

assert map.x?.a=null  //it'll be safe,the null exception will be silent.it's the best way in Groovy.


No comments: