Iterate and print content of groovy closures

﹥>﹥吖頭↗ 提交于 2019-12-02 11:37:42

问题


In a loop I create 4 closures and add them to a list:

closureList = []
for (int i=0; i<4; i++) {
    def cl = {
        def A=i;
    }
    closureList.add(cl)
}
closureList.each() {print  it.call()println "";};

This results in the following output:

4
4
4
4

But I would have expected 0,1,2,3 instead. Why does the 4 closures have the same value for A?


回答1:


Yeah, this catches people out, the free variable i is getting bound to the last value in the for loop, not the value at the time the closure was created.

You can either, change the loop into a closure based call:

closureList = (0..<4).collect { i ->
    { ->
        def a = i
    }
}
closureList.each { println  it() }

Or create an extra variable that gets re-set every time round the loop, and use that:

closureList = []

for( i in (0..<4) ) {
    int j = i
    closureList << { ->
        def a = j
    }
}
closureList.each { println  it() }

In both of these variants the variable closed by the closure is created afresh each time round the loop, so you get the result you'd expect



来源:https://stackoverflow.com/questions/22145763/iterate-and-print-content-of-groovy-closures

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