我希望能够做到这样的事情:
def closure = {
def a // create new variable, but ONLY if not created yet
if (a == null) {
a = 0
}
a++
print a
}
closure() // prints 1
closure() // prints 2
closure() // prints 3, etc...
我想在闭包中创建INSIDE变量,而不是在外部范围内。
答案 0 :(得分:7)
这可能是无效的答案,但外部范围不需要是全局的;它可以在一个函数内部,或者甚至是一个匿名函数,如:
def closure = {
def a
return {
if (a == null) a = 1
println a++
}
}()
closure() // prints 1
closure() // prints 2
closure() // prints 3, etc...
周围匿名函数的目的只是为a
变量赋予范围而不污染全局范围。请注意,该函数在定义后立即进行评估。
这样,a
的范围对于该闭包实际上是“私有的”(因为它是唯一一个在评估外部函数后引用它的人)。但是在第一次closure()
调用之前定义了变量,所以这可能不是你想要的。
答案 1 :(得分:1)
您可以这样做:
def closure = {
if( !delegate.hasProperty( 'a' ) ) {
println "Adding a to delegate"
delegate.metaClass.a = 0
}
delegate.a++
println delegate.a
}
closure() // prints 1
closure() // prints 2
closure() // prints 3, etc...
但这是一个令人讨厌的副作用,如果你不小心它会咬你(并且任何类型的多线程都会失败)