4

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?

Malte Schwerhoff
  • 12,684
  • 4
  • 41
  • 71

2 Answers2

5

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()
pedrofurla
  • 12,763
  • 1
  • 38
  • 49
  • I didn't downvote, but maybe it was because it's needlessly verbose when you can just write `ms.mapValues(_.toSet)` – Luigi Plinge Jul 09 '12 at 03:42
  • 1
    I don't really care who down voted, only why. In my opinion the verbosity is not the point of the question nor the answer so it shouldn't be a reason for down voting. – pedrofurla Jul 09 '12 at 15:28
  • It's a bit of a pity that you have to iterate over the map, but it looks as if that's the way to go. – Malte Schwerhoff Jul 09 '12 at 19:41
2

How about using mapValues to change the Set alone?

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681