[英]Groovy list apply closure
Simple question. 简单的问题。 I'm to write a void "apply" which perform Closure on each element of the List.
我要编写一个空的“应用”,对列表的每个元素执行闭包。
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)
}
}
Do You have any idea what is wrong with that? 您知道这有什么问题吗?
The problem with your code is that the closure {it++}
increments every element in the List by 1, but the result is not saved anywhere. 您的代码的问题在于,闭包
{it++}
将List中的每个元素加1,但是结果没有保存在任何地方。 I guess what you want to do is create a new List that contains the result of applying this closure to each element of the orginal List. 我猜您想做的是创建一个新列表,其中包含将此闭合应用于原始列表的每个元素的结果。 If so, you should use
collect
instead of each
. 如果是这样,则应使用
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)
}
}
Alternative answer (not so Java-like): 替代答案(不像Java):
class Lista {
def apply = { list, closure -> list.collect(closure) }
def main = {
println apply([1,2,3,8,3,2,1], {it + 1})
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.