【问题标题】:Meaning of -= and += in Scala Trait definitionScala Trait 定义中 -= 和 += 的含义
【发布时间】:2016-03-04 12:07:23
【问题描述】:

我正在从本书Scala in Action 中学习 Scala,在这一章中作者正在解释 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 traits


    【解决方案1】:

    它们只是方法的名称。 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)
    

    请注意,在您的示例中,中缀语法用于调用 underlying 上的方法。例如:underlying find docunderlying.find(doc) 相同。

    【讨论】:

      猜你喜欢
      • 2013-11-26
      • 2015-08-07
      • 2016-09-12
      • 2013-12-23
      • 2023-03-21
      • 1970-01-01
      • 2023-03-04
      • 2021-09-13
      • 1970-01-01
      相关资源
      最近更新 更多