Why groovy closure refers to for loop iteration counter with reference

夙愿已清 提交于 2019-12-13 07:47:24

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!