What is the syntax for adding an element to a scala.collection.mutable.Map?
Solution 1:
The point is that the first line of your codes is not what you expected.
You should use:
val map = scala.collection.mutable.Map[A,B]()
You then have multiple equivalent alternatives to add items:
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))
And starting Scala 2.13
:
scala> map.addOne("k4" -> "v4")
res5: map.type = HashMap(k1 -> v1, k2 -> v2, k3 -> v3, k4 -> v4)
Solution 2:
As always, you should question whether you truly need a mutable map.
Immutable maps are trivial to build:
val map = Map(
"mykey" -> "myval",
"myotherkey" -> "otherval"
)
Mutable maps are no different when first being built:
val map = collection.mutable.Map(
"mykey" -> "myval",
"myotherkey" -> "otherval"
)
map += "nextkey" -> "nextval"
In both of these cases, inference will be used to determine the correct type parameters for the Map instance.
You can also hold an immutable map in a var
, the variable will then be updated with a new immutable map instance every time you perform an "update"
var map = Map(
"mykey" -> "myval",
"myotherkey" -> "otherval"
)
map += "nextkey" -> "nextval"
If you don't have any initial values, you can use 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
Solution 3:
When you say
val map = scala.collection.mutable.Map
you are not creating a map instance, but instead aliasing the Map type.
map: collection.mutable.Map.type = scala.collection.mutable.Map$@fae93e
Try instead the following:
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))
Solution 4:
Create a new immutable map:
scala> val m1 = Map("k0" -> "v0")
m1: scala.collection.immutable.Map[String,String] = Map(k0 -> v0)
Add a new key/value pair to the above map (and create a new map, since they're both immutable):
scala> val m2 = m1 + ("k1" -> "v1")
m2: scala.collection.immutable.Map[String,String] = Map(k0 -> v0, k1 -> v1)
Solution 5:
var test = scala.collection.mutable.Map.empty[String, String]
test("myKey") = "myValue"