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

Łukasz Lew picture Łukasz Lew · Feb 18, 2011 · Viewed 49.9k times · Source

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

Answer

Kevin Wright picture Kevin Wright · Feb 19, 2011

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.