Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert immutable.Map to mutable.Map in Scala?

How can I convert immutable.Map to mutable.Map in Scala so I can update the values in Map?

like image 523
Łukasz Lew Avatar asked Feb 18 '11 15:02

Łukasz Lew


People also ask

How do I convert a mutable map to immutable map in Scala?

You can use myMap. toMap to convert an a mutable map into immutable in Scala 2.8 and later versions.

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.

Is map mutable in Scala?

Maps are classified into two types: mutable and immutable. By default Scala uses immutable Map. In order to use mutable Map, we must import scala.


1 Answers

The cleanest way would be to use the mutable.Map varargs factory. Unlike the ++ approach, this uses the CanBuildFrom mechanism, and so has the potential to be more efficient if library code was written to take advantage of this:

val m = collection.immutable.Map(1->"one",2->"Two") val n = collection.mutable.Map(m.toSeq: _*)  

This works because a Map can also be viewed as a sequence of Pairs.

like image 191
Kevin Wright Avatar answered Sep 24 '22 09:09

Kevin Wright