是一个+ in + =在Map上的前缀运算符=?

Ste*_*eve 7 scala

在Martin Odersky的"Scala编程"一书中,第一章有一个简单的例子:

var capital = Map("US" -> "Washington", "France" -> "Paris")
capital += ("Japan" -> "Tokyo")
Run Code Online (Sandbox Code Playgroud)

第二行也可以写成

capital = capital + ("Japan" -> "Tokyo")
Run Code Online (Sandbox Code Playgroud)

我很好奇+ =符号.在Map类中,我没有找到+ =方法.我在一个自己的例子中能够做同样的行为

class Foo() {
    def +(value:String) = {
        println(value)
        this
    }
}

object Main {
  def main(args: Array[String]) = {
   var foo = new Foo()
   foo = foo + "bar"
   foo += "bar"
  }
}
Run Code Online (Sandbox Code Playgroud)

我在问自己,为什么+ =符号是可能的.如果类Foo中的方法被称为test,则它不起作用.这导致我使用前缀表示法.分配符号(=)的+前缀表示法是?有人可以解释这种行为吗?

Rex*_*err 9

如果你有一个返回相同对象的符号方法,那么追加equals将执行操作和赋值(作为一个方便的快捷方式).您也可以始终覆盖符号方法.例如,

scala> class Q { def ~#~(q:Q) = this }
defined class Q

scala> var q = new Q
q: Q = Q@3d511e

scala> q ~#~= q
Run Code Online (Sandbox Code Playgroud)


mic*_*ebe 5

// Foo.scala
class Foo {
  def +(f: Foo) = this
}

object Foo {
  def main(args: Array[String]) {
    var f = new Foo
    f += f
  }
}
Run Code Online (Sandbox Code Playgroud)

产量scalac -print Foo.scala:

package <empty> {
  class Foo extends java.lang.Object with ScalaObject {
    def +(f: Foo): Foo = this;
    def this(): Foo = {
      Foo.super.this();
      ()
    }
  };
  final class Foo extends java.lang.Object with ScalaObject {
    def main(args: Array[java.lang.String]): Unit = {
      var f: Foo = new Foo();
      f = f.+(f)
    };
    def this(): object Foo = {
      Foo.super.this();
      ()
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,编译器只是将其转换为赋值和方法调用.