collections – 如何使用groovy集合的collect()方法调用具有多个参数的闭包?

假设我有一个闭包:

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

现在我想循环遍历整数集合的每个项目,用5增加它,并将新元素保存到新集合:

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

现在我希望通过使用增量闭包来实现相同的结果.我怎样才能做到这一点?

应该是这样的(下面的代码错误):

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

相关文章

背景:    8月29日,凌晨4点左右,某服务告警,其中一个...
https://support.smartbear.comeadyapi/docs/soapui/steps/g...
有几个选项可用于执行自定义JMeter脚本并扩展基线JMeter功能...
Scala和Java为静态语言,Groovy为动态语言Scala:函数式编程,...
出处:https://www.jianshu.com/p/ce6f8a1f66f4一、一些内部...
在运行groovy的junit方法时,报了这个错误:java.lang.Excep...