Groovy: 数组中的`{}`有什么问题?

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

我希望结果是:

111
222

但实际结果是

222

您可以 运行 在 https://groovyide.com/playground

我哪里错了?

{} 是一个“空”(无操作,单元数)闭包而不是空映射(例如在 JS 中)。

改用空映射的文字:[:];例如

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

那么为什么在两个不同的闭包上设置 属性 最终会改变 两个闭包保持相同的价值?在闭包上设置 属性 正在更改闭包的 Binding。而且由于两个闭包都是 在相同的范围内,它们共享相同的绑定。因此第二个 id=222 赋值覆盖第一个。

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