Groovy closure not capturing static closure variable

偶尔善良 提交于 2019-12-24 04:57:49

问题


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'


来源:https://stackoverflow.com/questions/21814923/groovy-closure-not-capturing-static-closure-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!