假设我有一个闭包:
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/