向groovy闭包传递参数

向groovy闭包传递参数,groovy,closures,Groovy,Closures,编写了以下工作正常的代码: def teams = ['x', 'y', 'z'] def list = [ [id:1, team1: 'x', team2:'y' ], [id:2, team1: 'z', team2:'y' ]] def function = { teams.inject( [:]) { result, team -> result[team] = list.findAll { team in

编写了以下工作正常的代码:

def teams = ['x', 'y', 'z']
def list = [ [id:1, team1: 'x', team2:'y' ], [id:2, team1: 'z', team2:'y' ]]
def function = { 
    teams.inject( [:]) { result, team ->  
            result[team] = list.findAll { 
                team in [it.team1, it.team2] 
            }.size()
            result 
    }
}
println function()
结果输出如下:

[x:1, y:2, z:1]
现在,尝试将条件作为闭包传递给
函数
,如下所示:

def function = { closure -> 
    teams.inject( [:]) { result, team ->
        result[team] = list.findAll(closure).size()
        result
    }
}

def t = { team in [it.team1, it.team2] }

println function(t)
但它下面说的是错误<代码>团队在上下文中可用

捕获:groovy.lang.MissingPropertyException:没有这样的属性:类的团队:TestClose groovy.lang.MissingPropertyException:没有这样的属性:team for class:TestClose 在testclosure$\u run\u closure3.doCall(testclosure.groovy:8) 在testclosure$\u run\u closure2$\u closure6.doCall(testclosure.groovy:6) 在testclosure$\u run\u closure2.doCall(testclosure.groovy:6) 运行(testclosure.groovy:12)


有指针吗?

将所有必需参数传递到闭包的直接方法:

def teams = ['x', 'y', 'z']
def list = [ [id:1, team1: 'x', team2:'y' ], [id:2, team1: 'z', team2:'y' ]]

def function = { closure -> teams.inject( [:]) { result, team ->  
    result[team] = list.findAll{closure(team,it)}.size() 
    result 
} }

def t = {x1,x2-> x1 in [x2.team1, x2.team2]}

println function(t)
或者您可以使用
再水化
,但无法访问闭合参数:

def f = {_x,_y, closure->
    def x = _x
    def y = _y
    closure.rehydrate(this,this,this).call()
}


println f(111,222, {x+y})   //this works
println f(111,222, {_x+_y}) //this fails

我的意思是,当我在
closure
上进行另一个名为
curry
groovy配方时,如下所示:

def团队=['x','y','z']
def list=[[id:1,team1:'x',team2:'y'],[id:2,team1:'z',team2:'y']]
def function={closure->teams.inject([:]){result,team->result[team]=list.findAll(closure.curry(team)).size();result}
def t={param1,it->param1在[it.team1,it.team2]}
println函数(t)

谢谢你,达格特。我完全忽略了
findAll{..}
,正在尝试
findAll(..)