Close

Groovy Operators - Safe Navigation Operator

[Updated: Dec 6, 2018, Created: Dec 5, 2018]

The Safe Navigation Operator (?.) is used to avoid a NullPointerException.

This operator should be used when we have a reference to an object which is needed to be verified for not being null before accessing its methods or properties:

def obj = .....
def x =obj.?aMethod()
def y = obj.?aPropty
The safe navigation operator will simply return null if the reference object is null instead of throwing an NullPointerException. So In above example if obj is null, no NullPointerException will be thrown and x and y will be assigned to null.

Example

A Java class

groovy-safe-navigation-operator/src/Employee.java

public class Employee {
  String name;
  String dept;

  public Employee(String name, String dept) {
      this.name = name;
      this.dept = dept;
  }

  @Override
  public String toString() {
      return "Employee{" +
              "name='" + name + '\'' +
              ", dept='" + dept + '\'' +
              '}';
  }
}

Without Safe Navigation operator

/src/WithoutSafeNavOp.groovy

void displayEmployeeNameLength(Employee emp) {
    printf "employee: %s, name: %s, name length: %s%n",
            emp, emp.name, emp.name.length()
}

displayEmployeeNameLength(new Employee("Sara", "Admin"))
displayEmployeeNameLength(null);
displayEmployeeNameLength(new Employee(null, null))

Output

employee: Employee{name='Sara', dept='Admin'}, name: Sara, name length: 4
Caught: java.lang.NullPointerException
java.lang.NullPointerException
at WithoutSafeNavOp.displayEmployeeNameLength(WithoutSafeNavOp.groovy:2)
at WithoutSafeNavOp$displayEmployeeNameLength.callCurrent(Unknown Source)
at WithoutSafeNavOp.run(WithoutSafeNavOp.groovy:7)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

With Safe Navigation operator

src/WithSafeNavOp.groovy

void displayEmployeeNameLength(Employee emp) {
    printf "employee: %s, name: %s, name length:: %s%n",
            emp, emp?.name, emp?.name?.length()
}

displayEmployeeNameLength(new Employee("Sara", "Admin"))
displayEmployeeNameLength(null);
displayEmployeeNameLength(new Employee(null, null))

Output

employee: Employee{name='Sara', dept='Admin'}, name: Sara, name length:: 4
employee: null, name: null, name length:: null
employee: Employee{name='null', dept='null'}, name: null, name length:: null

Example Project

Dependencies and Technologies Used:

  • Groovy 2.5.3
  • JDK 11
Safe Navigation Operator Example Select All Download
  • groovy-safe-navigation-operator
    • src
      • WithSafeNavOp.groovy

    See Also