2012-01-09 54 views
2

簡單的問題。我要寫一個void「apply」,它在List的每個元素上執行Closure。Groovy list applied closure

class Lista { 

    def applay(List l, Closure c){ 
    return l.each(c) 
    } 

    static main(args) { 
    Lista t = new Lista() 
    List i = [1,2,3,8,3,2,1] 
    Closure c = {it++} 
    println t.applay(i, c) 
    } 
} 

你有什麼想法嗎?

回答

3

您的代碼存在的問題是關閉{it++}將列表中的每個元素都加1,但結果不保存在任何地方。我想你想要做的是創建一個新的列表,其中包含將該閉包應用到原始列表的每個元素的結果。如果是這樣,您應該使用collect而不是each

class Lista { 

    def applay(List l, Closure c){ 
    return l.collect(c) // I changed this line 
    } 

    static main(args) { 
    Lista t = new Lista() 
    List i = [1,2,3,8,3,2,1] 
    Closure c = {it + 1} // I changed this line 
    println t.applay(i, c) 
    } 
} 
+0

運行完美。謝謝。 – user1138470 2012-01-09 12:44:12

+0

@ user1138470考慮[接受](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)答案,或至少* upvoting - 這不僅僅是一個溫暖對Don來說模糊不清,它也有助於未來的訪問者知道答案有幫助。謝謝! – 2012-01-11 13:07:14

2

備選答案(未所以Java類):

class Lista { 
    def apply = { list, closure -> list.collect(closure) } 

    def main = { 
     println apply([1,2,3,8,3,2,1], {it + 1}) 
    } 
}