Is this NPE-related behavior expected for the Groovy secure navigation operator?

In our code today, I met an exception where it trim()throws NPE when doing something like someString?.toLowerCase().trim(). I found this curious, as I had the impression that the safe nav op would immediately burst on null, instead of continuing to name things in the chain. So, sorting through the groovy command line a bit ...

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

That everything is fine and dandy. But they removed the safe nav op on band ...

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)

? a null, , -, NPE b, nav op. , null var2, , null b, c NPE.

nav op , Groovy? , !

+3
1

. . - .

:

a?.b.c

:

java.lang.NullPointerException: Cannot get property: c on null object
        at CommandLine.run(CommandLine.groovy:10)

, , , , "a" , , a.anything NPE. , "a.b" , :

null.c

, , Groovy , , , NPE.

+4

Source: https://habr.com/ru/post/1720746/


All Articles