【问题标题】:Idiomatic/Groovy way to add two maps, either of which may be null添加两个地图的惯用/Groovy 方式,其中任何一个都可能为空
【发布时间】:2019-05-04 20:34:20
【问题描述】:

我有以下地图:

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:方法 java.util.LinkedHashMap#plus 的方法重载不明确。 由于以下之间的原型重叠,无法解析为 [null] 调用哪个方法: [接口 java.util.Collection] [接口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 的人可以告诉我一个更好的方法吗?谢谢!

【问题讨论】:

    标签: dictionary groovy idioms


    【解决方案1】:

    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 表示,您就可以使用它。

    【讨论】:

    • 啊,我是如此接近。我试过了,但没有用()括起来。现在,对于加分,我想我可以对公共部分做同样的事情(如果它是空的)?
    • 这正是我想要的——谢谢。
    • 正确。如果config['commons'] 可能为空,那么用?: 包裹它是个好主意。
    猜你喜欢
    • 1970-01-01
    • 2012-04-21
    • 2012-06-01
    • 1970-01-01
    • 2011-08-18
    • 2011-06-17
    • 1970-01-01
    • 2020-02-04
    • 2020-04-23
    相关资源
    最近更新 更多