问题
I am wondering why the following two snippets output different results. It looks like the iteration counter is a special case handled by closure.
int i = 1
def closures = (1..3).collect {
return { println i; ++i }
}
for (int j = 0; j < 3; ++j) {
closures += { println j }
}
closures*.call()
1
2
3
3
3
3
回答1:
It's a question of when the variable is updated
In the first example, i is only incremented when the closure is executed, so even though each closure is bound to the same instance of i, each output is different
In the second example, j is incremented outside the closures, so by the time you run them, the for loop has finished, and the value of j is 3
来源:https://stackoverflow.com/questions/44967051/why-groovy-closure-refers-to-for-loop-iteration-counter-with-reference