简体   繁体   中英

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

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) }]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM