迭代和打印groovy闭包的内容
在循环中,我创建了4个闭包并将它们添加到列表中:迭代和打印groovy闭包的内容,groovy,closures,Groovy,Closures,在循环中,我创建了4个闭包并将它们添加到列表中: closureList = [] for (int i=0; i<4; i++) { def cl = { def A=i; } closureList.add(cl) } closureList.each() {print it.call()println "";}; 但我本以为是0,1,2,3。为什么4个闭包的值相同?是的,自由变量i绑定到for循环中的最后一个值,而不是创建闭包时的值 您可以
closureList = []
for (int i=0; i<4; i++) {
def cl = {
def A=i;
}
closureList.add(cl)
}
closureList.each() {print it.call()println "";};
但我本以为是0,1,2,3。为什么4个闭包的值相同?是的,自由变量i
绑定到for循环中的最后一个值,而不是创建闭包时的值
您可以将循环更改为基于闭包的调用:
closureList = (0..<4).collect { i ->
{ ->
def a = i
}
}
closureList.each { println it() }
closureList=(0。。
{ ->
def a=i
}
}
closureList.each{println it()}
或者创建一个额外的变量,每次循环时都会重新设置该变量,并使用该变量:
closureList = []
for( i in (0..<4) ) {
int j = i
closureList << { ->
def a = j
}
}
closureList.each { println it() }
closureList=[]
对于(0..是的,自由变量i
将绑定到for循环中的最后一个值,而不是创建闭包时的值
您可以将循环更改为基于闭包的调用:
closureList = (0..<4).collect { i ->
{ ->
def a = i
}
}
closureList.each { println it() }
closureList=(0。。
{ ->
def a=i
}
}
closureList.each{println it()}
或者创建一个额外的变量,每次循环时都会重新设置该变量,并使用该变量:
closureList = []
for( i in (0..<4) ) {
int j = i
closureList << { ->
def a = j
}
}
closureList.each { println it() }
closureList=[]
对于(i)在(0。。