Skip to main content
Blog

Avoid NullPointerException: Safe Navigation with Groovy

By 25 september 2015januari 30th, 2017No Comments

We know it’s all too common in Java to get a NullPointerException when we use an object reference which is null. This happens when our code tries to access a method or field of an object, or element of an array when there’s no instance present – e.g. it refers to null.

class Animal {
String name
Animal parent
}

def animal = new Animal(name: "Bella") // no parent

We might get an Animal instance from the outside and we need to get the name of the parent.

def parentName = animal.parent.name
// BLAM! java.lang.NullPointerException:
// Cannot get property 'name' on null object

Parent is null. Usually as a precaution we have to check for null beforehand.

if (animal.parent != null) {
def parentName = animal.parent.name
}

You can see that if we need the name of the grandparent, there are even more references which could be null.

def grandParentName = animal.parent.parent.name

Groovy logoWe need a safe way to navigate through references we might expect to be null. Fortunately, with Groovy this is very easy. Use the Safe Navigation (or null-safe) operator which guards against NullPointerExceptions. This is just a question mark (?) before the dot (.)

animal?.name

A small little gem, but a great feature of Groovy.

// instead of checking for nulls the Java way
if (animal.parent != null && animal.parent.parent != null) {
def grandParentName = animal.parent.parent.name
}

// or using the Groovy truth
if (animal.parent && animal.parent.parent) {
def grandParentName = animal.parent.parent.name
}

// use safe navigation
def grandParentName = animal.parent?.parent?.name

// and in combination with Elvis
grandParentName = animal.parent?.parent?.name ?: "Unknown"

Original article