groovy Safe Navigation Operator Basic usage


Example

Groovy's safe navigation operator allows to avoid NullPointerExceptions when accessing to methods or attributes on variables that may assume null values. It is equivalent to nullable_var == null ? null : nullable_var.myMethod()

def lst = ['foo', 'bar', 'baz']

def f_value = lst.find { it.startsWith('f') }    // 'foo' found
f_value?.length()    // returns 3

def null_value = lst.find { it.startsWith('z') }    // no element found. Null returned

// equivalent to  null_value==null ? null : null_value.length()
null_value?.length()    // no NullPointerException thrown

// no safe operator used
​null_value.length()​​​​​    // NullPointerException thrown