惯用的 Scala Map upsert

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/408602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 16:18:28  来源:igfitidea点击:

Idiomatic Scala Map upsert

scalascala-collections

提问by Dave Ray

I'm working with a map in Scala and doing the usual "if there's no value associated with a key, create it, put it in the map and return it":

我正在 Scala 中使用地图并执行通常的“如果没有与键关联的值,则创建它,将其放入地图并返回它”:

def alphaMemory(key : AlphaMemoryKey) = {
    var am = map.getOrElse(key, null)
    if(am == null) {
        am = new AlphaMemory(key)
        map.put(key, am)
    }
    am
}

To me, this does not feel like idiomatic Scala code. It feels like Java. Is there a more succinct way of writing this? It looked like maybe I could override Map.default() to insert the new value and return it. Not sure though.

对我来说,这不像是惯用的 Scala 代码。感觉像Java。有没有更简洁的写法?看起来也许我可以覆盖 Map.default() 以插入新值并返回它。虽然不确定。

Thanks!

谢谢!

回答by sblundy

mutable.Maphas V):V" rel="noreferrer">getOrElseUpdatewhich does exactly what you want, no idiom necessary.

mutable.Maphas V):V" rel="noreferrer">getOrElseUpdatewhich 正是你想要的,不需要成语。