Scala地图:如何添加新条目



我已经创建了我的scala映射为:

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

然后我尝试添加条目为:

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

在代码的这一部分之后,我看到一个仍然是空的。而且,b是类型:

Pattern: B: IndexedSeq[Any]

我需要一个地图来添加条目和相同或不同的地图,以返回以后在代码中使用。但是,我不能为此使用" var"。关于此问题的任何见解以及如何解决此问题?

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

不要创建一个空的地图,使用.map.filter

创建Map[String, String]
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
      }
    }
    

最新更新