Scala 地图:如何添加新条目

Scala map : How to add new entries

我将我的 Scala 映射创建为:

val A:Map[String, String] = Map()

然后我尝试将条目添加为:

val B = AttributeCodes.map { s =>

    val attributeVal:String = <someString>
    if (!attributeVal.isEmpty)
    {
      A + (s -> attributeVal)
    }
    else
      ()
  }

在这部分代码之后,我看到 A 仍然是空的。并且,B 的类型为:

Pattern: B: IndexedSeq[Any]

我需要一个地图来添加条目,以及 return 中相同或不同的地图,以便稍后在代码中使用。但是,我不能为此使用 "var" 。对此问题有何见解以及如何解决?

Scala 在许多情况下使用不可变性,并鼓励您也这样做。

不要创建空地图,创建 Map[String, String].map.filter

val A = AttributeCodes.map { s =>
      val attributeVal:String = <someString>
      s -> attributeVal
}.toMap.filter(e => !e._1.isEmpty && !e._2.isEmpty)

在 Scala 中,默认的 Map 类型是不可变的。 <Map> + <Tuple> 创建一个添加了附加条目的新地图实例。

有两种解决方法:

  1. 改用scala.collection.mutable.Map

    val A:immutable.Map[String, String] = immutable.Map()
    
    AttributeCodes.forEach { s =>
      val attributeVal:String = <someString>
      if (!attributeVal.isEmpty){
        A.put(s, attributeVal)
      }
    }
    
  2. 使用折叠在不可变映射中创建:

    val A: Map[String,String] = AttributeCodes.foldLeft(Map(), { m, s =>
      val attributeVal:String = <someString>
      if (!attributeVal.isEmpty){
        m + (s -> attributeVal)
      } else {
        m
      }
    }