Search code examples
groovynullintvariable-assignmentprimitive

Groovy: What happens if the safe navigation operator returns null on a primitive assignment?


Character parrot = null
int hp = parrot?.hp
if (hp < 0) {
    print (parrot+" is pining for the fjords.")
}

Essentially, what happens in the second line? Is hp set to null, even though it's a primitive? Do we get an exception? Or is it, for some reason, set to 0?

(Research indicates that (null < 0) == true, so that part is fine.)

Also, do things change if we instead write:

Character parrot = null
if (parrot?.hp < 0) {
    print (parrot+" is pining for the fjords.")
}

Solution

    1. you get:

      org.codehaus.groovy.runtime.typehandling.GroovyCastException:
           Cannot cast object 'null' with class 'null' to class 'int'.
           Try 'java.lang.Integer' instead
      
    2. Yes. As you say, null < 0 so you get the output:

      null is pining for the fjords