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")
To create a mutable map, either use an import statement to bring it into scope, or specify the full path to the scala. collection. mutable. Map class when you create an instance.
// Creation of Map having key-value. // pairs of type (String, Int) val mapMut = scala.collection.mutable.Map[String, Int]() println( "Empty Map: " + mapMut)
There are two kinds of Maps, the immutable and the mutable. The difference between mutable and immutable objects is that when an object is immutable, the object itself can't be changed. By default, Scala uses the immutable Map. If you want to use the mutable Map, you'll have to import scala.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With