2014-03-03 70 views
0

在循环中我创建了4封,并将它们添加到列表的打印内容:迭代和Groovy闭

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有相同的值?

回答

1

是的,this catches people out,自由变量i已绑定到for循环中的最后一个值,而不是创建闭包时的值。

您可以,环路变成一个封闭的基于电话:

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

或创建一个额外的变量被重新设置一轮循环每一次,并使用:

closureList = [] 

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

在这两种变体中,每次围绕闭环关闭的变量都会重新创建,因此您会得到期望的结果