[英]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
主要問題是[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.