I came across an exception in our code today where trim()
throws a NPE when doing something like someString?.toLowerCase().trim()
. This got me curious, as I was under the impression that the safe nav op would break immediately upon null
rather than continuing to call things in the chain. So tinkering a bit in command line groovy...
groovy> def a = null
groovy> def getB = {
groovy> return 'b'
groovy> }
groovy> def getC = {
groovy> return 'c'
groovy> }
groovy> def var1 = a?.b?.c
groovy> var1
===> null
Which is all fine and dandy. But removed the safe nav op on the b
, and...
groovy> def a = null
groovy> def getB = {
groovy> return 'b'
groovy> }
groovy> def getC = {
groovy> return 'c'
groovy> }
groovy> def var2 = a?.b.c
groovy> var2
groovy> go
Caught: java.lang.NullPointerException: Cannot get property: c on null object
at CommandLine.run(CommandLine.groovy:10)
What's going on here? a
is null, so if anything, the NPE should be thrown by b
, but that's what the safe nav op is there for. I would have expected execution to stop at this point and return null
to var2
, but instead it seems the null
gets passed down through b
, causing c
to NPE.
Is my understanding of the safe nav op wrong here, or is this a bug in Groovy? Thanks folks!