如何使用值初始化 Scala 不可变哈希图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3898900/
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
How to initialize a Scala immutable hashmap with values?
提问by Ivan
What's the syntax to set immutable hashmap contents on initialization?
在初始化时设置不可变哈希图内容的语法是什么?
For example, if I was willing to hardcode an array, I'd write:
例如,如果我愿意对数组进行硬编码,我会写:
val a = Array (0, 1, 2, 3)
val a = 数组 (0, 1, 2, 3)
What's the analogue for immutable hashmaps (say I want it to contain 0->1 and 2->3 pairs) (in Scala 2.8)?
不可变哈希图的类似物是什么(假设我希望它包含 0->1 和 2->3 对)(在 Scala 2.8 中)?
回答by Arjan Blokzijl
Do you mean something like this?
你的意思是这样的吗?
scala> val m = collection.immutable.HashMap(0 -> 1, 2 -> 3)
m: scala.collection.immutable.HashMap[Int,Int] = Map((0,1), (2,3))
scala> m.get(0)
res0: Option[Int] = Some(1)
scala> m.get(2)
res1: Option[Int] = Some(3)
scala> m.get(1)
res2: Option[Int] = None
回答by samthebest
To create from a collection (remember NOT to have a newkeyword)
从集合创建(记住不要有new关键字)
val result: HashMap[Int, Int] = HashMap(myCollection: _*)

