Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@CompileStatic gives NullPointerException

Tags:

groovy

Why just annotating with @CompileStatic makes the below code to give NullPointerException?

class GroovyEach {
    static def main(args) {
        List items = null

        items.each {
            println 'hello'
        }

    }
}

Below code gives exception.

import groovy.transform.CompileStatic

@CompileStatic
class GroovyEach {
    static def main(args) {
        List items = null

        items.each {
            println 'hello'
        }

    }
}

Stacktrace:

Exception in thread "main" java.lang.NullPointerException
    at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:1372)
    at trial.GroovyEach.main(GroovyEach.groovy:10)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
like image 973
John Jai Avatar asked Oct 19 '22 15:10

John Jai


1 Answers

This is the inverse of an older question. When compiled statically, items is of type List, when not compiled statically the type is NullObject, which retrieves the iterator in a null-safe fashion. This is trivial to demonstrate.

This works

class GroovyEach {
    static void main(String[] args) {
        List items = null
        (org.codehaus.groovy.runtime.NullObject) items
    }
}

this fails with [Static type checking] - Inconvertible types: cannot cast java.util.List to org.codehaus.groovy.runtime.NullObject

@groovy.transform.CompileStatic
class GroovyEach {
    static void main(String[] args) {
        List items = null
        (org.codehaus.groovy.runtime.NullObject) items
    }
}
like image 51
Keegan Avatar answered Oct 22 '22 23:10

Keegan