首页 文章

Groovy闭包没有捕获静态闭包变量

提问于
浏览
1

有人可以解释一下为什么对 qux 的调用失败了吗?它在创建时似乎没有捕获静态闭包变量 foo 的名称 . 如果我故意将名称分配给变量,如 baz 那么它可以工作,或者如果我通过类调用它 . 我认为这个变量捕获也适用于闭包类变量,但我必须遗漏一些东西 .

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

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

[编辑]最后,如果 foo 只是一个方法,它也可以按我的预期工作:

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

1 回答

  • 2

    好像this bug . 如果将 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'
    

相关问题