Is + in + = on the map the operator prefix =?

Martin Odersky's book Scala Programming has a simple example in the first chapter:

var capital = Map("US" -> "Washington", "France" -> "Paris") capital += ("Japan" -> "Tokyo") 

The second line can also be written as

 capital = capital + ("Japan" -> "Tokyo") 

I'm curious about the designation + =. In the Map class, I did not find the + = method. I managed the same behavior in my own example as

 class Foo() { def +(value:String) = { println(value) this } } object Main { def main(args: Array[String]) = { var foo = new Foo() foo = foo + "bar" foo += "bar" } } 

I ask myself why the notation + = is possible. This does not work if, for example, a method of the Foo class is called test. This led me to prefix notation. Is prefix notation + for destination sign (=)? Can anyone explain this behavior?

+7
scala
source share
3 answers

If you have a symbolic method that returns the same object, then adding equals will do the operation and assignment (as a convenient shortcut for you). You can 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 
+9
source share
 // Foo.scala class Foo { def +(f: Foo) = this } object Foo { def main(args: Array[String]) { var f = new Foo f += f } } 

The output of 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(); () } } } 

As you can see, the compiler simply converts it to the destination and method call.

+5
source share

+ = is the operator where the default implementation uses the + operator. Therefore, in most cases, it already does exactly what you want.

0
source share

All Articles