Передача аргументов к заводному закрытию - PullRequest
1 голос
/ 11 мая 2019

Написал приведенный ниже код, который работает нормально:

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 ]

1 голос
/ 11 мая 2019

прямой способ передать все необходимые параметры для закрытия:

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
0 голосов
/ 11 мая 2019

Имеется в виду, когда я продолжил с groovy recipe, называемым curry на 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.curry(team)).size() ; result } }
def t = { param1, it  -> param1 in [it.team1, it.team2] }

println function(t)
...