Groovy closure not capturing static closure variab

2019-07-22 17:17发布

问题:

Can someone please explain why the call to qux fails? It doesn't seem to capture the name of the static closure variable foo when it is created. If I purposely assign the name to a variable as in baz it works, or if I call it through the class. I thought this variable capture should work for closure class variables too but I must be missing something.

class C {
  static foo = { "foo" }
  static bar = { C.foo() }
  static baz = { def f = foo; f() }
  static qux = { foo() }
}    
println C.foo() //works
println C.bar() //works
println C.baz() //works
println C.qux() //fails

I also tried this as a test and it had no problem capturing the i variable:

class C {
  static i = 3
  static times3 = { "foo: ${it * i}" }
}    
println C.times3(2) //works

[edit] Lastly, if foo is simply a method, it also works as I expected:

class C {
  static foo() { "foo" }
  static bar = { foo() }
}    
println C.bar() //works

回答1:

It seems like this bug. If you treat foo as an attribute, it works:

class C {
  static foo = { "foo" }
  static bar = { C.foo() }
  static baz = { def f = foo; f() }
  static qux = { foo.call() }
}    
assert C.foo() == 'foo'
assert C.bar() == 'foo'
assert C.baz() == 'foo'
assert C.qux() == 'foo'