Idiomatic/Groovy 添加两个地图的方法,其中一个可能为空

Idiomatic/Groovy way to add two maps, either of which may be null

我有以下地图:

configs = [
    common : [
            foo : '123',
            bar : '456'
    ],
    dev : [
            foo : '789',
            bar : '012'
    ],
    test : null
]

当我将 dev 添加到 common 时,效果很好 - 来自 common 的值被来自 dev 的值覆盖。正是我想要的。

dev = configs['common'] + configs['dev']
println dev
// --> [foo:789, bar:012]

但是,如果我对 test 进行同样的尝试,我会收到以下错误:

groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method java.util.LinkedHashMap#plus. Cannot resolve which method to invoke for [null] due to overlapping prototypes between: [interface java.util.Collection] [interface java.util.Map]

我可以通过执行以下操作使其工作:

test = [:]
test = configs['common']==null ? test : test + configs['common']  // First add common bits
test = configs['test']==null ? test : test + configs['test']  // Then override with environment specific bits
println test
// --> [foo:123, bar:456]

但这看起来又丑又臃肿。

有更好的 Groovy-fu 可以告诉我更好的方法吗?谢谢!

config['test'] == null 时,您可以使用 Elvis operator 将空映射带入方程。考虑以下示例:

def configs = [
  common : [
    foo : '123',
    bar : '456'
  ],
  dev : [
    foo : '789',
    bar : '012'
  ],
  test : null
]


def dev = configs['common'] + (configs['dev'] ?: [:])
println dev

def test = configs['common'] + (configs['test'] ?: [:])
println test

输出:

[foo:789, bar:012]
[foo:123, bar:456]

只要您希望一个值可以用 null 来表示,您就可以使用它。