Groovy seems to have very unpleasant behavior related to "Groovy Beans" and closures, which can mask local variables under certain circumstances.
Is this known behavior and is there some kind of documentation somewhere that details this stuff? I spent a lot of time figuring out what wasnβt working ...
Consider the following code:
class TestClass { def doIt(Closure closure) { closure.setDelegate(this) closure.call() } def getRevision() { return "testclass revision" } } def testIt() { def revision = "testit revision" println "1: " + revision + " (expect: testit)" TestClass tester = new TestClass() tester.doIt { println "2: " + getRevision() + " (expect: testclass)" } println "3: " + revision + " (expect: testit)" tester.doIt { println "4: " + revision + " (expect: testit)" revision = getRevision() println "5: " + revision + " (expect: testclass)" println "6: ${getRevision()} (expect: testclass)" println "7: " + getRevision() + " (expect: testclass)" }
Running this code gives the following output:
1: testit revision (expect: testit) 2: testclass revision (expect: testclass) 3: testit revision (expect: testit) 4: testit revision (expect: testit) 5: testit revision (expect: testclass) 6: testit revision (expect: testclass) 7: testit revision (expect: testclass) 8: testit revision (expect: testclass) 9: testclass revision (expect: testclass) 10: testclass revision (expect: testclass) 11: testit revision (expect: testclass)
My main problem is 5/6/7. It seems that just using the local revision
variable in the closure βhidesβ the getRevision()
method on the deletion and replaces it with a bean-line auto- getRevision()
to match the revision
property. βIf I don't use the revision
variable, getRevision()
calls getRevision()
n't cause behavior bean.
Any insights or links to documentation will be appreciated!
source share