Groovy列表应用闭包

时间:2012-01-09 10:46:06

标签: list groovy

简单的问题。我要编写一个void“apply”,它对List的每个元素执行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)
  }
}

你知道这有什么问题吗?

2 个答案:

答案 0 :(得分:3)

代码的问题在于,闭包{it++}会将List中的每个元素递增1,但结果不会保存在任何位置。我想你想要做的是创建一个新的List,其中包含将此闭包应用于原始List的每个元素的结果。如果是,则应使用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)
  }
}

答案 1 :(得分:2)

替代答案(不像Java那样):

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

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