如何使用值初始化 Scala 不可变哈希图?

发布于 2024-09-26 19:17:23 字数 184 浏览 0 评论 0原文

在初始化时设置不可变哈希图内容的语法是什么?

例如,如果我愿意对数组进行硬编码,我会写:

val a = 数组(0,1,2,3)

不可变哈希图的类似物是什么(假设我希望它包含 0->1 和 2->3 对)(在 Scala 2.8 中)?

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)

What's the analogue for immutable hashmaps (say I want it to contain 0->1 and 2->3 pairs) (in Scala 2.8)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

累赘 2024-10-03 19:17:23

你的意思是这样的吗?


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

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
伪装你 2024-10-03 19:17:23

从集合创建(记住不要有 new 关键字)

val result: HashMap[Int, Int] = HashMap(myCollection: _*)

To create from a collection (remember NOT to have a new keyword)

val result: HashMap[Int, Int] = HashMap(myCollection: _*)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文