2010-05-06 88 views
7

在從馬丁Odersky的書「編程在斯卡拉」沒有在第一章一個簡單的例子:是Map中的+ in + =前綴運算符=?

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

第二行也可以寫成

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

我很好奇+ =表示法。在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" 
    } 
} 

我在質疑自己,爲什麼+ =表示法是可能的。例如,如果Foo類中的方法稱爲測試,則不起作用。這導致我的前綴符號。是賦值符號(=)的+前綴符號嗎?有人可以解釋這種行爲嗎?

回答

9

如果您有一個返回相同對象的符號方法,則追加equals將執行操作和賦值(作爲您的便捷快捷方式)。您也可以始終重寫符號方法。例如,

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

scala> var q = new Q 
q: Q = [email protected] 

scala> q ~#~= q 
+0

非常感謝。隨着你的回答,我還了解到,這適用於多個角色(如〜#〜)。 – Steve 2010-05-06 08:03:40

0

+ =是一個運算符,其中默認實現使用+運算符。因此在大多數情況下,它已經完全按照您的要求進行。

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

object Foo { 
    def main(args: Array[String]) { 
    var f = new Foo 
    f += f 
    } 
} 

輸出的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(); 
    () 
    } 
    } 
} 

正如你所看到的只是編譯器將其轉換爲分配和方法的調用。