我创建了一个 MultiMap

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

在填充条目后,必须将其传递给需要 Map[String, Set[String]] 的函数。直接传递 ms 不起作用,并尝试通过 toMap 将其转换为不可变映射
ms.toMap[String, Set[String]]

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

这是否可以在不手动迭代 ms 并将所有条目插入新的不可变映射的情况下解决?

最佳答案

似乎问题是可变集。所以变成不可变的集合是有效的:

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

或者甚至更好地遵循 Daniel Sobral 的建议:
scala> (ms mapValues { _.toSet }).toMap[String, Set[String]]
res7: scala.collection.immutable.Map[String,Set[String]] = Map()

关于scala - 可变 MultiMap 到不可变 Map,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11386918/

10-11 22:31
查看更多