【发布时间】: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
【问题讨论】: