How can I convert immutable.Map to mutable.Map in Scala?
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.
val myImmutableMap = collection.immutable.Map(1->"one",2->"two")
val myMutableMap = collection.mutable.Map() ++ myImmutableMap
Starting Scala 2.13
, via factory builders applied with .to(factory)
:
Map(1 -> "a", 2 -> "b").to(collection.mutable.Map)
// collection.mutable.Map[Int,String] = HashMap(1 -> "a", 2 -> "b")
How about using collection.breakOut?
import collection.{mutable, immutable, breakOut}
val myImmutableMap = immutable.Map(1->"one",2->"two")
val myMutableMap: mutable.Map[Int, String] = myImmutableMap.map(identity)(breakOut)