Skip to content

Instantly share code, notes, and snippets.

@dexterous
Created March 3, 2011 05:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dexterous/852379 to your computer and use it in GitHub Desktop.
Save dexterous/852379 to your computer and use it in GitHub Desktop.
scoping gotcha with Groovy Categories
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!
class Foo {
private final boo;
Foo(boo) { this.boo = boo }
def bar() { "original $boo" }
}
class FooCategory {
def static bar(Foo self) { "categorical ${self.boo}" }
}
@dexterous
Copy link
Author

@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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment