I'm trying to execute code which creates n (here 10) differently named folders and executes some functions in them. They are supposed to be used in combination with Jenkins and be executed in parallel.
The problem is that the following code produces only "10" as output and not the numbers from 0 to 9 as I would have expected:
ps = [:]
for (int i = 0; i < 10; ++i) {
ps["${i}"] = {
println(i)
}
}
for (int i = 0; i < 10; i++) {
ps["${i}"]()
}
How does the code have to be altered to print the index at which the map has its entry? I think I can't pass something as an argument since in Jenkins the map is executed by calling
parallel ps
The closure in the for
-loop captures the variable i
and not it's value. You have create a fresh var to capture in each iteration. E.g.
for (int i = 0; i < 10; ++i) {
def v = i
ps[i.toString()] = {
println(v)
}
}
Random side note: using GStrings as map keys is bad (they are not immutable).
If you "groovy-fy" this code, it becomes shorter and you don't have to deal with the problem. E.g.
def ps = (0..9).collectEntries { i ->
[i.toString(), { -> println(i) }]
}
ps.values()*.call()