简单的问题。我要编写一个 void“apply”,它对列表的每个元素执行闭包。
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)
}
}
你知道这有什么问题吗?
最佳答案
您的代码的问题在于,闭包 {it++}
将 List 中的每个元素递增 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)
}
}
关于list - Groovy 列表应用闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8787218/