2016-03-04 28 views
2

我正在從書Scala in Action學習Scala,在本章中作者正在解釋Traits。解釋有以下代碼塊,其中我無法弄清楚特徵定義中的 - =和+ =的含義Updatable- =和+ =在Scala中的含義特徵定義

請幫助!

package com.scalainaction.mongo 
import com.mongodb.{DBCollection => MongoDBCollection } 
import com.mongodb.DBObject 

class DBCollection(override val underlying: MongoDBCollection) 
extends ReadOnly 
trait ReadOnly { 
    val underlying: MongoDBCollection 
    def name = underlying getName 
    def fullName = underlying getFullName 
    def find(doc: DBObject) = underlying find doc 
    def findOne(doc: DBObject) = underlying findOne doc 
    def findOne = underlying findOne 
    def getCount(doc: DBObject) = underlying getCount doc 
} 
trait Updatable extends ReadOnly { 
    def -=(doc: DBObject): Unit = underlying remove doc 
    def +=(doc: DBObject): Unit = underlying save doc 
} 

回答

6

它們只是方法的名稱。 Scala中的方法名稱不限於像Java等其他語言中的字母,數字和下劃線。所以,名稱如+=-=是方法的完全可以接受的名稱。

請注意,在斯卡拉方法和運營商之間沒有區別。運營商只是方法。調用具有一個參數的方法有兩種語法:使用圓括號中的點和參數的「正常」語法和中綴語法。

val a = 3 
val b = 2 

// The infix syntax for calling the + method 
val c = a + b 

// Normal method call syntax for calling the + method 
val d = a.+(b) 

注意,在你的榜樣,綴語法被用來調用underlying方法。例如:underlying find docunderlying.find(doc)相同。