[英]groovy .. passing closures as parameter to another closure
By way of example .. 举个例子..
def data = [1,2,3,4,5,6,7]
def someFilter = {it-> it % 2 == 0}
def newData = data.findAll{it,someFilter ->
someFilter(it)
}
newData
gives me an error .. 给我一个错误..
The current scope already contains a variable of the name someFilter at line: 5, column: 27 当前作用域已经在第5行,第27列包含名称为someFilter的变量。
is it possible to pass a closure (maybe anonomously) to another closure ? 是否可以将一个闭包(也许是匿名地)传递给另一个闭包?
Thanks 谢谢
You can pass closures. 您可以传递闭包。 I believe this is what you had intended:
我相信这就是您想要的:
def data = [1,2,3,4,5,6,7]
def someFilter = {it-> it % 2 == 0}
def newData = data.findAll someFilter
newData // results in [2, 4, 6]
To pass a closure anonymously, 要匿名传递闭包,
def newData = data.findAll { it % 2 == 0 }
The it
variable is implicitly defined for the first argument passed to the closure; 为传递给闭包的第一个参数隐式定义了
it
变量; you only need to use the arrow syntax for multiple variables or for giving the first argument a different name, eg 您只需要对多个变量使用箭头语法或为第一个参数赋予不同的名称,例如
def newData = data.findAll { nbr -> nbr % 2 == 0 }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.