Scala Trait 定义中 -= 和 += 的含义

Meaning of -= and += in Scala Trait definition

我正在从书中学习 Scala Scala in Action,作者在该章中解释了 Traits。解释有以下代码块,其中我无法弄清楚Trait definitionnof Updatable

中-=和+=的含义

请帮忙!

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
}

它们只是方法的名称。 Scala 中的方法名称等不限于字母、数字和下划线,就像在其他语言中一样 Java。因此,+=-= 之类的名称是完全可以接受的方法名称。

请注意,在 Scala 中,方法和运算符之间没有区别。运算符只是方法。有两种调用具有一个参数的方法的语法:"normal" 语法使用圆括号中的点和参数,以及中缀语法。

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) 相同。