Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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") 
like image 308
Koala3 Avatar asked Oct 22 '10 03:10

Koala3


People also ask

How do you make a mutable map in Scala?

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.

What is the syntax of creating map in Scala?

// Creation of Map having key-value. // pairs of type (String, Int) val mapMut = scala.collection.mutable.Map[String, Int]() println( "Empty Map: " + mapMut)

What is Scala collection mutable map?

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.


1 Answers

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) 
like image 178
Eastsun Avatar answered Sep 23 '22 02:09

Eastsun