Converting mutable to immutable map

Jeriho picture Jeriho · May 12, 2010 · Viewed 61.9k times · Source
private[this]object MMMap extends  HashMap[A, Set[B]] with MultiMap[A, B]

How convert it to immutable?

Answer

Rex Kerr picture Rex Kerr · May 12, 2010

The immutable hierarchy doesn't contain a MultiMap, so you won't be able to use the converted structure with the same convenient syntax. But if you're happy to deal with key/valueset pairs, then:

If you just want a mutable HashMap, you can just use x.toMap in 2.8 or collection.immutable.Map(x.toList: _*) in 2.7.

But if you want the whole structure to be immutable--including the underlying set!--then you have to do more: you need to convert the sets along the way. In 2.8:

x.map(kv => (kv._1,kv._2.toSet)).toMap

In 2.7:

collection.immutable.Map(
  x.map(kv => (kv._1,collection.immutable.Set(kv._2.toList: _*))).toList: _*
)