Groovy闭包不捕获静态闭包变量 [英] Groovy closure not capturing static closure variable

查看:233
本文介绍了Groovy闭包不捕获静态闭包变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释为什么致电 qux 失败?它在创建时似乎不捕获静态闭包变量 foo 的名称。如果我有意将名称分配给变量,如 baz ,它工作,或者如果我通过类调用它。我认为这个变量捕捉应该为闭包类变量工作,但我必须缺少一些东西。

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 变量的问题:

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


最后,如果 foo ,它也按照我的预期工作:

[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


推荐答案

这似乎是这个错误。如果您将 foo 当作属性,它的工作原理:

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'

这篇关于Groovy闭包不捕获静态闭包变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆