Groovy Safe Navigation Operator Is a Null Check Not a Truth Check
Blog Logo
on
read
The Groovy Safe Navigation Operator is awesome. No one likes getting NPEs all over the place or having to add lots of if/else blocks to check for nulls. We use it frequently in the Grails application at my company and given the depth of the domain class relationships it is really useful (I would be surprised if any Groovy developer didn’t swear by this operator’s utility). Where I have seen this operator cause confusion is in the belief that it is a groovy truth navigator instead of a null safe navigator. I know I have been bitten by this a time or two in the beginning. Most of the time it has shown up in our project it was around domain class collections. If you have a Grails domain class that has a collection with nothing in it, accessing the collection will return an empty collection and not a null value. What does this mean in context of the safe navigator? What it means is that the collection will fly past the operator (since it is not null) and the next method call will be evaluated. If the next method call bombs on empty collections then you get a NoSuchElementException or something similar. To get around this you may just have to use our friend the ternary operator instead. See below for a concrete example.