2014-03-03 68 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() } 

在這兩種變體中,每次圍繞閉環關閉的變量都會重新創建,因此您會得到期望的結果