【问题标题】:Groovy closure not capturing static closure variableGroovy 闭包不捕获静态闭包变量
【发布时间】:2014-03-15 21:55:15
【问题描述】:

谁能解释一下为什么调用 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

【问题讨论】:

    标签: groovy closures


    【解决方案1】:

    好像是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'
    

    【讨论】:

    • 在错误数据库中很好地找到了!我同意这听起来正是那个问题。看起来它也已经存在了一段时间。
    • 计划在 groovy 3 中修复。有了特性和新的 MOP,我认为 v3 会摇滚。
    猜你喜欢
    • 2019-10-14
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多