What is the syntax for adding an element to a scala.collection.mutable.Map?

Koala3 picture Koala3 · Oct 22, 2010 · Viewed 115.5k times · Source

What is the syntax for adding an element to a scala.collection.mutable.Map ?

Here are some failed attempts:

val map = scala.collection.mutable.Map

map("mykey") = "myval"

map += "mykey" -> "myval"

map.put("mykey","myval")

Answer

Eastsun picture Eastsun · Oct 22, 2010

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)