Groovy’s null safe operator

The more years I get under my belt as a programmer the more I appreciate the smaller things a language has to offer. Today I want to look at Groovy’s null safe operator. When you want to crawl an object graph you always have to be worried about the dreaded null pointer exception. First I want to take a look at this example in ColdFusion. In this example we are looking at the body of a method where we load up a user object. We want to grab the city of the user object but in each step of the object graph we need to make sure that call is not null before preceding.

In Groovy we can do this shorthand by using the null safe operator (?.). If the variable before the question mark is null it will not proceed and actually returns null for you. We could even shorten this statement more but you get the idea.

The Groovy language has so many little things like this that I am really starting to love. What are some of your favorite features in the language?

Hi, I’m Dan Vega. I am a Software Engineer living just outside of one of my favorite places in the world, Cleveland, Ohio. I am a self-taught programmer who firmly believes that you can accomplish anything in this life if you put your mind to it, roll up your sleeves and are willing to put in the work.

I have been writing software for over 18+ years now and I use my knowledge, passion, and influence to help other developers achieve their goals. I teach online and currently, have over 30,000 students.

When I am not writing software, I have a number of things that really keep me busy. I love to read books, listen to podcasts and watch online courses. I have a real thirst for knowledge and it consumes me every single day of the week. I also love to run & lift heavy weights which keep me balanced throughout the week.

Please note: I reserve the right to delete comments that are offensive or off-topic.