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)
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With