Search

Dark theme | Light theme

August 17, 2009

Groovy Goodness: Safe Navigation to Avoid NullPointerException

Little things in live can be such a joy. The safe navigation operator in Groovy is such a little thing. Suppose we have modelled a simple domain like this:

class Company {
    Address address
    String name
}

class Address {
    Street street
    String postalCode
    String city
}

class Street { 
    String name
    String number
    String additionalInfo
}

We want to display the streetname, but we don't know if all object instances are available. To avoid a NullPointerException we write the following code:

// company can be null.
if (company != null && company.getAddress() != null && company.getAddress().getStreet() != null) {
    println company.address.street.name
}

Groovy adds the safe navigation operator to shorten all this to:

// company can be null.
println company?.address?.street?.name

If one of the objects was null, the output of the total statement is null. We will not get any NullPointerExceptions.