Created
March 3, 2011 05:28
-
-
Save dexterous/852379 to your computer and use it in GitHub Desktop.
scoping gotcha with Groovy Categories
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def f = new Foo('hello') | |
assert f.bar() == 'original hello' | |
use(FooCategory) { assert f.bar() == 'categorical hello' } | |
class Baz { | |
def quux(boo) { new Foo(boo).bar() } | |
} | |
use(FooCategory) { assert new Baz().quux('no') == 'original no' } // fails as quux returns 'categorical no' even though Foo.bar is not called in this lexical scope! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Foo { | |
private final boo; | |
Foo(boo) { this.boo = boo } | |
def bar() { "original $boo" } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FooCategory { | |
def static bar(Foo self) { "categorical ${self.boo}" } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@olabini pointed out to me that Groovy's categories are runtime-scoped, not lexically-scoped
run this at http://groovyconsole.appspot.com/script/433001 or https://ideone.com/V1Z9E