scala 将可变映射转换为不可变映射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2817055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 02:08:06  来源:igfitidea点击:

Converting mutable to immutable map

scalaimmutabilitymutablescala-collections

提问by Jeriho

private[this]object MMMap extends  HashMap[A, Set[B]] with MultiMap[A, B]

How convert it to immutable?

如何将其转换为不可变的?

采纳答案by Rex Kerr

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:

不可变层次结构不包含 MultiMap,因此您将无法使用具有相同方便语法的转换结构。但是,如果您乐于处理键/值集对,那么:

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

如果你只想要一个 mutable HashMap,你可以x.toMap在 2.8 或collection.immutable.Map(x.toList: _*)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:

但是如果你希望整个结构是不可变的——包括底层的集合!——那么你必须做更多的事情:你需要一路转换集合。在 2.8 中:

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

In 2.7:

在 2.7:

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

回答by michael.kebe

scala> val mutableMap = new HashMap[Int, String]
mutableMap: scala.collection.mutable.HashMap[Int,String] = Map()

scala> mutableMap += 1 -> "a"
res5: mutableMap.type = Map((1,a))

scala> mutableMap
res6: scala.collection.mutable.HashMap[Int,String] = Map((1,a))

scala> val immutableMap = mutableMap.toMap
immutableMap: scala.collection.immutable.Map[Int,String] = Map((1,a))

scala> immutableMap += 2 -> "b"
<console>:11: error: reassignment to val
       immutableMap += 2 -> "b"
                ^

回答by Fahad Siddiqui

You can use myMap.toMapto convert an a mutable map into immutable in Scala 2.8 and later versions.

myMap.toMap在 Scala 2.8 及更高版本中,您可以使用将可变映射转换为不可变映射。

Looking at definition of toMapfrom documentation:

查看toMap文档中的定义:

def toMap[T, U](implicit ev: A <:< (T, U)): immutable.Map[T, U] = {
  val b = immutable.Map.newBuilder[T, U]
  for (x <- self) b += x
  b.result
}

回答by Harish Gajapathy

You can just to the following

你可以只到以下

val imm_map = MMMap.toMap