Groovy

Avoid NullPointerException: Safe Navigation with Groovy

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

We 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"

2 comments

  1. Hi Ted,

    I need some clarifications on groovy things if you kind enough to do…
    Please Elaborate the followings,i searched but didn’t find any satisfactory solution.
    why some of the Variables have Type defined and other don’t?
    Why some methods have lines under the methods?
    Clibuilder allows us to invoke non-existing one-letter methods which turns into one letter shorcut. what does it mean?

    Like

  2. Hi Usman, thanks for commenting. As for your questions, whether using def or an actual type is explained in http://groovy-lang.org/semantics.html#_variable_definition
    When you say methods are underlined, I think you are referring to how some IDE’s — such as GGTS — might display those lines when it cannot statically determine whether or not those method are there. What you mean with your last question I honestly don’t know.

    Like

Comments are closed.