向groovy闭包传递参数

时间:2019-05-11 16:08:36

标签: 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 [it.team1, it.team2] 
            }.size()
            result 
    }
}
println function()

结果如下:

[x:1, y:2, z:1]

现在,尝试将条件作为闭包传递给function,如下所示:

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)

但是它说下面的错误。 team在上下文中可用。

  

捕获:groovy.lang.MissingPropertyException:无此类属性:类团队:testclosure   groovy.lang.MissingPropertyException:无此类属性:类团队:testclosure       在testclosure $ _run_closure3.doCall(testclosure.groovy:8)       在testclosure $ _run_closure2 $ _closure6.doCall(testclosure.groovy:6)       在testclosure $ _run_closure2.doCall(testclosure.groovy:6)       在testclosure.run(testclosure.groovy:12)

有指针吗?

2 个答案:

答案 0 :(得分:1)

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

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)

或者您可以使用rehydrate,但不能访问闭包参数:

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

答案 1 :(得分:0)

表示我在groovy recipe上进行另一个名为curry的{​​{1}}的情况,如下所示:

closure