地图上 += 中的 + 是 = 的前缀运算符吗? [英] is the + in += on a Map a prefix operator of =?
问题描述
在 Martin Odersky 的Programming in Scala"一书中,第一章有一个简单的例子:
In the book "Programming in Scala" from Martin Odersky there is a simple example in the first chapter:
var capital = Map("US" -> "Washington", "France" -> "Paris")
capital += ("Japan" -> "Tokyo")
第二行也可以写成
capital = capital + ("Japan" -> "Tokyo")
我对 += 符号很好奇.在类 Map 中,我没有找到 += 方法.我能够在自己的示例中执行相同的行为,例如
I am curious about the += notation. In the class Map, I didn't found a += method. I was able to the same behaviour in an own example like
class Foo() {
def +(value:String) = {
println(value)
this
}
}
object Main {
def main(args: Array[String]) = {
var foo = new Foo()
foo = foo + "bar"
foo += "bar"
}
}
我在问自己,为什么 += 符号是可能的.例如,如果类 Foo 中的方法称为 test ,则它不起作用.这让我想到了前缀符号.+ 是赋值符号 (=) 的前缀符号吗?有人可以解释这种行为吗?
I am questioning myself, why the += notation is possible. It doesn't work if the method in the class Foo is called test for example. This lead me to the prefix notation. Is the + a prefix notation for the assignment sign (=)? Can somebody explain this behaviour?
推荐答案
如果您有一个返回相同对象的符号方法,那么附加 equals 将执行操作和赋值(作为您方便的快捷方式).您也可以始终覆盖符号方法.例如,
If you have a symbolic method that returns the same object, then appending equals will perform the operation and assignment (as a handy shortcut for you). You may also always override the symbolic method. For example,
scala> class Q { def ~#~(q:Q) = this }
defined class Q
scala> var q = new Q
q: Q = Q@3d511e
scala> q ~#~= q
这篇关于地图上 += 中的 + 是 = 的前缀运算符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!