Mutable MultiMap to immutable Map

2019-06-25 09:48发布

问题:

I create a MultiMap

val ms =
  new collection.mutable.HashMap[String, collection.mutable.Set[String]]()
  with collection.mutable.MultiMap[String, String]

which, after it has been populated with entries, must be passed to a function that expects a Map[String, Set[String]]. Passing ms directly doesn't work, and trying to convert it into a immutable map via toMap

ms.toMap[String, Set[String]]

yields

Cannot prove that (String, scala.collection.mutable.Set[String]) <:< (String, Set[String]).

Can this be solved without manually iterating over ms and inserting all entries into a new immutable map?

回答1:

It seems that the problem is mutable set. So turning into immutable sets works:

scala> (ms map { x=> (x._1,x._2.toSet) }).toMap[String, Set[String]]
res5: scala.collection.immutable.Map[String,Set[String]] = Map()

Or even better by following Daniel Sobral suggestion:

scala> (ms mapValues { _.toSet }).toMap[String, Set[String]]
res7: scala.collection.immutable.Map[String,Set[String]] = Map()


回答2:

How about using mapValues to change the Set alone?