簡體   English   中英

如何使用groovy集合的collect()方法調用多個參數的閉包?

[英]How to call a closure with multiple parameters from collect() method of a groovy collection?

假設我有一個閉包:

def increment = {value, step ->
   value + step 
}

現在我想循環遍歷整數集合的每個項目,用5增加它,並將新元素保存到新集合:

def numbers = [1..10]
def biggerNumbers = numbers.collect {
      it + 5
} 

現在我希望通過使用increment閉包來實現相同的結果。 我怎樣才能做到這一點?

應該是這樣的(下面的代碼錯誤):

def biggerNumbers = numbers.collect increment(it, 5) //what's the correct name of 'it'??

你的問題的解決方案是在閉包中嵌套你的增量調用:

def biggerNumbers = numbers.collect {increment(it, 5)}

如果你想將一個premade閉包傳遞給collect你應該讓它與collect兼容 - 接受一個參數:

def incrementByFive = {it + 5}
def biggerNumbers = numbers.collect incrementByFive

mojojojo有正確的答案,但只是以為我想補充的是,這看起來像一個很好的候選人柯里 (特別是使用rcurry

如果你有:

def increment = {value, step ->
   value + step 
}

然后,您可以使用以下方法調整此函數的右側參數:

def incrementByFive = increment.rcurry 5

然后,你可以這樣做:

def numbers = 1..10
def biggerNumbers = numbers.collect incrementByFive

只是覺得它可能有趣;-)

主要問題是[1..10]創建了一個List<IntRange> ,你試圖增加它。 您應該直接在IntRange上collect (注意缺少括號):

(1..10).collect { it + 5 }

或者咖喱:

def sum = { a, b -> a + b }
(1..10).collect(sum.curry(5))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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