Details
-
Bug
-
Status: Closed
-
Minor
-
Resolution: Fixed
-
1.0-JSR-4
-
None
-
None
-
WinXP, JDK1.5
Description
There appears to be something odd going on with variable scope, possibly related to closures. I'm still learning Groovy, so can't at the moment help with diagnosis, but the problem code is as below:
import groovy.xml.DOMBuilder
def builder = DOMBuilder.newInstance()
def root = builder.rootElement() {
childElement() {
for(i in 0..10) {}
}
for(i in 0..10) {}
}
This code results in the following exception:
Caught: java.lang.NullPointerException
at test$_run_closure1_closure2.doCall(test.groovy:6)
at test$_run_closure1_closure2.doCall(test.groovy)
at test$_run_closure1.doCall(test.groovy:5)
at test$_run_closure1.doCall(test.groovy)
at test.run(test.groovy:3)
at test.main(test.groovy)
As far as I can tell, the loop variable within the closure somehow collides with the loop variable in the loop in the same scope level as the closure itself. My workaround at the moment is the following:
import groovy.xml.DOMBuilder
def builder = DOMBuilder.newInstance()
def root = builder.rootElement() {
childElement() {
for(i in 0..10) {}
}
{ // Dummy scope
for(i in 0..10) {}
}
}
Is this an issue, or is it a quirk of closures I haven't understood yet?
Charlie Dobbie.