简体   繁体   English

Groovy闭包未捕获静态闭包变量

[英]Groovy closure not capturing static closure variable

Can someone please explain why the call to qux fails? 有人可以解释为什么qux调用失败的原因吗? It doesn't seem to capture the name of the static closure variable foo when it is created. 创建静态闭包变量foo时,似乎没有捕获到它的名称。 If I purposely assign the name to a variable as in baz it works, or if I call it through the class. 如果我像在baz中一样故意将名称分配给变量,则它可以工作,或者通过类调用它。 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: 我也尝试将其作为测试,捕获i变量没有问题:

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: [edit]最后,如果foo只是一个方法,它也可以按照我的预期工作:

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

It seems like this bug . 好像是这个bug If you treat foo as an attribute, it works: 如果将foo作为属性,它将起作用:

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM