迭代并打印groovy封闭的内容 [英] Iterate and print content of groovy closures
问题描述
在一个循环中,我创建了4个闭包并将它们添加到列表中:
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 "";};
这将产生以下输出:
4
4
4
4
但是我本来希望是0、1、2、3。为什么4个闭包的A值相同?
But I would have expected 0,1,2,3 instead. Why does the 4 closures have the same value for A?
推荐答案
是的,这吸引了人们,自由变量 i
绑定到for循环中的最后一个值,而不是创建闭包时的值。
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
这篇关于迭代并打印groovy封闭的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!