Reputation: 21389
Wrote the below code which is working fine:
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()
Results the following output:
[x:1, y:2, z:1]
Now, trying to passing condition as closure to the function
as below:
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)
But it says below error. team
is available in the context though.
Caught: groovy.lang.MissingPropertyException: No such property: team for class: testclosure groovy.lang.MissingPropertyException: No such property: team for class: testclosure at testclosure$_run_closure3.doCall(testclosure.groovy:8) at testclosure$_run_closure2$_closure6.doCall(testclosure.groovy:6) at testclosure$_run_closure2.doCall(testclosure.groovy:6) at testclosure.run(testclosure.groovy:12)
Any pointers?
Upvotes: 2
Views: 1956
Reputation: 21389
Mean while I proceeded with another groovy recipe
called curry
on the closure
as shown below:
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.curry(team)).size() ; result } }
def t = { param1, it -> param1 in [it.team1, it.team2] }
println function(t)
Upvotes: 1
Reputation: 28634
the straight way to pass all required params to closure:
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)
or you could use rehydrate
, but you can't access closure parameters:
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
Upvotes: 2