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.

1
2
3
4
5
6
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.

1
2
3
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.

1
2
3
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.

1
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.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
// 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"
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Ted Vinke

Ted is a Java software engineer with a passion for Web development and JVM languages and works for First8, a Java Web development company in the Netherlands.
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button