Slimy43
Slimy43

Reputation: 341

Groovy list in a map not showing a loop count properly

I have this code in Groovy;

def execution = []
def executor =[:]
for(loopcount=1;loopcount<4;loopcount++){
    executor.executor = 'jmeter'
    executor.scenario = 'scenario' + loopcount
    println executor.scenario
    executor.concurrency = 2
    execution.add(executor)
}
execution.each{
    println executor.scenario
}

It is a list of three maps, all the same apart from the scenario suffix increments. I am expecting;

scenario1
scenario2
scenario3
scenario1
scenario2
scenario3

But I get;

scenario1
scenario2
scenario3
scenario3
scenario3
scenario3

It's definitely adding three different maps in the list because the .each command is returning three values. And they're definitely different values in executor.scenario because the println in the loop is giving the correct '1, 2, 3' count. But why don't they stay as different values in the list?

I've also tried execution.push(executor) but that gives the same results. For context, this yaml is what I'm aiming for eventually;

---
execution:
- executor: "jmeter"
  scenario: "scenario1"
  concurrency: 2
- executor: "jmeter"
  scenario: "scenario2"
  concurrency: 2
- executor: "jmeter"
  scenario: "scenario3"
  concurrency: 2

And apart from the scenario count the rest of it works fine.

Upvotes: 0

Views: 100

Answers (1)

daggett
daggett

Reputation: 28564

problem:

def execution = []
def executor =[:]
for(loopcount=1;loopcount<4;loopcount++){
    execution.add(executor) // <<-- this line adds the same variable to the list 4 times
}

to fix this - declare executor inside the for loop

def execution = []
for(loopcount=1;loopcount<4;loopcount++){
    def executor =[:]       // <<-- creates a new object in a loop
    execution.add(executor) // <<-- adds new object to a list
}

probably to make it more clear, let me specify what [] and [:] means:

def execution = new ArrayList()
for(loopcount=1;loopcount<4;loopcount++){
    def executor = new LinkedHashMap()
    execution.add(executor)
}

however you could declare the variable before the loop but you have to assign a new object into it inside loop

def execution = []
def executor
for(loopcount=1;loopcount<4;loopcount++){
    executor = [:]
    execution.add(executor)times
}

Upvotes: 1

Related Questions