簡體   English   中英

常規列表應用關閉

[英]Groovy list apply 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)
  }
}

您知道這有什么問題嗎?

您的代碼的問題在於,閉包{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)
  }
}

替代答案(不像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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM