问题
I would like to be able to do something like this:
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...
I want to create the variable INSIDE the closure, not in outer scope.
回答1:
This may be an invalid answer but the outer scope doesn't need to be global; it can be inside a function for example, or even an anonymous function like:
def closure = {
def a
return {
if (a == null) a = 1
println a++
}
}()
closure() // prints 1
closure() // prints 2
closure() // prints 3, etc...
The purpose of the surrounding anonymous function is just to give scope to the a variable without polluting the global scope. Notice that that function is being evaluated immediately after its definition.
This way, the scope of a is effectively "private" to that closure (as it is the only one with a reference to it once the outer function has been evaluated). But the variable is being defined before the first closure() call, so this might not be what you are looking for.
回答2:
You can do something like this:
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...
But that's a nasty side-effect, and if you don't take care it's going to bite you hard (and any sort of multi-threading will fail horribly)
来源:https://stackoverflow.com/questions/8923950/groovy-how-to-remember-closures-variable-value-between-executions