Search code examples
jenkinsgroovyjenkins-workflowjenkins-pipeline

Groovy function call in a closure


How can I make a function call in a closure in Groovy? Currently trying this but it results in all iterations using the values from the last array element:

def branches = [:]
for (int i = 0; i < data.steps.size(); i++) {
    branches["${data.steps.get(i).name}"] = {
        myFunc(data.steps.get(i))
    }
}
parallel branches

Solution

  • That's a common gotcha

    This should work:

    def branches = data.steps.collectEntries { step ->
        [step.name, { myFunc(step) }]
    }
    parallel branches
    

    Or

    def branches = data.steps.inject([:]) { map, step ->
        map << [(step.name): { myFunc(step) }]
    }