collections - 如何从常规集合的 collect() 方法中调用具有多个参数的闭包?

标签 collections groovy closures

假设我有一个闭包:

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)}

如果您想将预制的闭包传递给 collect你应该让它与 collect 兼容- 接受单个参数,即:
def incrementByFive = {it + 5}
def biggerNumbers = numbers.collect incrementByFive

关于collections - 如何从常规集合的 collect() 方法中调用具有多个参数的闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7704371/

相关文章:

javascript - jQuery.ajax() 中的范围问题

c# - 测试集合是否包含基于特定属性的对象

java - 在 List<?> 中添加一个元素

groovy - 比较没有相等定义的对象列表

java - 在 Java/Groovy 中计算耗时

javascript - 闭包:函数返回后局部变量如何保持事件状态?

java - 关于ArrayList类中的fastRemove()方法

python - OrderedDict 键错误

groovy - UNET 堆栈中的动态路由

php - 有没有办法在 PHP 匿名函数中不捕获 $this?