-=和+;=的含义在Scala特征定义中
我从《Scala在行动中》(Scala in Action)一书中学习Scala,这一章是作者解释特征的一章。这个解释有下面的代码块,在其中我无法理解-=和+;=的含义在Scala特征定义中,scala,traits,Scala,Traits,我从《Scala在行动中》(Scala in Action)一书中学习Scala,这一章是作者解释特征的一章。这个解释有下面的代码块,在其中我无法理解updateable 请帮忙 package com.scalainaction.mongo import com.mongodb.{DBCollection => MongoDBCollection } import com.mongodb.DBObject class DBCollection(override val underlyi
updateable
请帮忙
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中,方法和运算符之间没有区别。运算符只是方法。调用具有一个参数的方法有两种语法:使用点和括号之间的参数的“普通”语法和中缀语法
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)
请注意,在您的示例中,中缀语法用于调用底层
上的方法。例如:基础查找文档
与基础查找(文档)
相同