将元素添加到scala.collection.mutable.Map的语法是什么?

将元素添加到scala.collection.mutable.Map的语法是什么?

以下是一些失败的尝试:

val map = scala.collection.mutable.Map map("mykey") = "myval" map += "mykey" -> "myval" map.put("mykey","myval") 

    关键是你的代码的第一行不是你所期望的。 你应该使用

     val map = scala.collection.mutable.Map[A,B]() 

    要么

     val map = new scala.collection.mutable.Map[A,B]() 

    代替。

     scala> val map = scala.collection.mutable.Map[String,String]() map: scala.collection.mutable.Map[String,String] = Map() scala> map("k1") = "v1" scala> map res1: scala.collection.mutable.Map[String,String] = Map((k1,v1)) scala> map += "k2" -> "v2" res2: map.type = Map((k1,v1), (k2,v2)) scala> map.put("k3","v3") res3: Option[String] = None scala> map res4: scala.collection.mutable.Map[String,String] = Map((k3,v3), (k1,v1), (k2,v2)) 

    和往常一样,你应该怀疑你是否真的需要一个可变的地图。

    不可变的映射是微不足道的:

     val map = Map( "mykey" -> "myval", "myotherkey" -> "otherval" ) 

    第一次构build时,可变映射并没有什么不同:

     val map = collection.mutable.Map( "mykey" -> "myval", "myotherkey" -> "otherval" ) map += "nextkey" -> "nextval" 

    在这两种情况下,都会使用推理来确定Map实例的正确types参数。

    您也可以在var保存一个不可变的映射,然后每次执行“更新”时都会使用新的不可变映射实例更新该variables。

     var map = Map( "mykey" -> "myval", "myotherkey" -> "otherval" ) map += "nextkey" -> "nextval" 

    如果你没有任何初始值,你可以使用Map.empty:

     val map : Map[String, String] = Map.empty //immutable val map = Map.empty[String,String] //immutable val map = collection.mutable.Map.empty[String,String] //mutable 

    当你说

     val map = scala.collection.mutable.Map 

    您不是创build地图实例,而是使用地图types的别名。

     map: collection.mutable.Map.type = scala.collection.mutable.Map$@fae93e 

    尝试改为以下内容:

     scala> val map = scala.collection.mutable.Map[String, Int]() map: scala.collection.mutable.Map[String,Int] = Map() scala> map("asdf") = 9 scala> map res6: scala.collection.mutable.Map[String,Int] = Map((asdf,9)) 
     var test = scala.collection.mutable.Map.empty[String, String] test("myKey") = "myValue" 

    创build一个新的不可变的地图:

     scala> val m1 = Map("k0" -> "v0") m1: scala.collection.immutable.Map[String,String] = Map(k0 -> v0) 

    添加一个新的键/值对上面的地图(并创build一个新的地图,因为它们都是不可变的):

     scala> val m2 = m1 + ("k1" -> "v1") m2: scala.collection.immutable.Map[String,String] = Map(k0 -> v0, k1 -> v1) 

    创build一个没有初始值的可变映射:

     scala> var d= collection.mutable.Map[Any, Any]() d: scala.collection.mutable.Map[Any,Any] = Map() 

    用初始值创build一个可变映射:

     scala> var d= collection.mutable.Map[Any, Any]("a"->3,1->234,2->"test") d: scala.collection.mutable.Map[Any,Any] = Map(2 -> test, a -> 3, 1 -> 234) 

    更新现有的键值:

     scala> d("a")= "ABC" 

    添加新的键值:

     scala> d(100)= "new element" 

    检查更新的地图:

     scala> d res123: scala.collection.mutable.Map[Any,Any] = Map(2 -> test, 100 -> new element, a -> ABC, 1 -> 234)