Scala Map:神秘的语法糖?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/680975/
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-09-13 16:19:51  来源:igfitidea点击:

Scala Map: mysterious syntactic sugar?

scalamapssyntactic-sugarscala-collections

提问by oxbow_lakes

I have just found out this syntax for a scala Map(used here in mutableform)

我刚刚发现了 Scala 的这种语法Map(此处以可变形式使用)

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 sugarbuilt 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?

现在我不确定这是否是语言内置的语法,或者这里是否发生了一些更基本的事情,涉及映射扩展了PartialFunction. 谁能解释一下?

回答by starblue

If you mean (it would be nice if you could be more explicit)

如果你的意思是(如果你能更明确一点就好了)

m("Hello") = 5

that is intended syntactic sugar for

那是为了语法糖

m.update("Hello", 5)

independent of what m is. This is analogous to

与 m 是什么无关。这类似于

m("Hello")

which is syntactic sugar for

这是语法糖

m.apply("Hello")

(I'm just reading "Programming in Scala".)

(我只是在读“在 Scala 中编程”。)

回答by Daniel Spiewak

@starblue is correct. Note that you can also do rather creative things with updatesuch as returning values otherthan what was assigned. For example:

@starblue 是正确的。请注意,您也可以对颇具创意的东西update比如返回值比分配。例如:

val a = Map(1 -> "one")      // an immutable Map[Int, String]
val b = a(2) = "two"
val c = b(5) = "five"
val d = c(1) = "uno"

d == Map(1 -> "uno", 2 -> "two", 5 -> "five")       // => true

This works because immutable.Map#updatereturns an instance of the new Map. It looks a little odd to the C-trained eye, but you get used to it.

这是有效的,因为immutable.Map#update返回了 new 的一个实例Map。对于受过 C 培训的人来说,这看起来有点奇怪,但你已经习惯了。