Iterate and print content of groovy closures

会有一股神秘感。 提交于 2019-12-02 03:13:32

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

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