Details
-
Type:
Bug
-
Status:
Closed
-
Priority:
Minor
-
Resolution: Fixed
-
Affects Version/s: 1.0-JSR-4
-
Fix Version/s: 1.0-JSR-5
-
Component/s: None
-
Labels:None
-
Environment:WinXP, JDK1.5
-
Number of attachments :
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.
jsr-05 has a brand new scoping and gives no longer a NPE here. In the new scoping the loop variable of the for is always a local variable of the loop. This means it is not visible outside, nor can it be shared with another loop.