Scala Map:神秘的语法糖?
我刚刚发现了 scala Map
的语法(这里以可变形式使用)
val m = scala.collection.mutable.Map[String, Int]()
m("Hello") = 5
println(m) //PRINTS Map(Hello -> 5)
现在我不确定这是否是语法糖内置于语言中,或者这里是否发生了更基本的事情,涉及映射扩展 PartialFunction
的事实。 有人能解释一下吗?
I have just found out this syntax for a scala Map
(used here in mutable form)
val m = scala.collection.mutable.Map[String, Int]()
m("Hello") = 5
println(m) //PRINTS Map(Hello -> 5)
Now I'm not sure whether this is syntactic sugar built in to the language, or whether something more fundamental is going on here involving the fact that a map extends a PartialFunction
. Could anyone explain?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你的意思是(如果你能更明确的话那就太好了)
这是
独立于 m 的语法糖。 这类似于
which is 语法糖
(我正在阅读“Scala 中的编程”。)
If you mean (it would be nice if you could be more explicit)
that is intended syntactic sugar for
independent of what m is. This is analogous to
which is syntactic sugar for
(I'm just reading "Programming in Scala".)
@starblue是正确的。 请注意,您还可以使用
update
做一些相当有创意的事情,例如返回除分配值之外的其他值。 例如:这是有效的,因为
immutable.Map#update
返回新Map
的实例。 对于受过 C 训练的人来说,这看起来有点奇怪,但你会习惯的。@starblue is correct. Note that you can also do rather creative things with
update
such as returning values other than what was assigned. For example:This works because
immutable.Map#update
returns an instance of the newMap
. It looks a little odd to the C-trained eye, but you get used to it.