groovy Safe Navigation Operator Basic usage

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any groovy Question?