Groovy collision between automatic getter agent, local variables and closure?

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)" } // expect to have been set to testclass value in previous closure println "8: " + revision + " (expect: testclass)" tester.doIt { println "9: ${getRevision()} (expect: testclass)" println "10: " + getRevision() + " (expect: testclass)" } println "11: " + revision + " (expect: testclass)" } testIt() 

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!

+6
source share
1 answer

Groovy closures have a resolveStrategy property that can be used to control permission order. The default strategy is to search for a property from the owner object and only if it is not found there to use the delegate. I believe that setting this parameter to DELEGATE_FIRST will lead to the expected behavior.

+1
source

Source: https://habr.com/ru/post/914251/


All Articles