osexp2000
osexp2000

Reputation: 3165

Groovy: what is wrong with the`{}` in array?

def hosts = [{}, {}]
hosts[0].id = 111
hosts[1].id = 222
println hosts[0].id
println hosts[1].id

I expect the result to be:

111
222

But the actual result is

222

You can run this in https://groovyide.com/playground

Where am I wrong?

Upvotes: 0

Views: 98

Answers (1)

Predominant
Predominant

Reputation: 1460

{} is an "empty" (no-op, single-arity) closure and not an empty map (like e.g. in JS).

Use the literal for an empty map instead: [:]; e.g.

def hosts = [[:], [:]]
hosts[0].id = 111
hosts[1].id = 222
println hosts[0].id
println hosts[1].id

So why does setting a property on two different closures end up changing both closures to hold the same value? Setting a property on a closure is changing the Binding of the closure. And since both closures are in the same scope they both share the same binding. Ergo the second id=222 assignment overrides the first one.

def hosts = [{}, {}]
println hosts*.binding
// → [groovy.lang.Binding@56f2bbea, groovy.lang.Binding@56f2bbea]

Upvotes: 4

Related Questions