自我型注释背后的Scala构造是什么?



我对以下代码有一个问题:

  trait Connection {
    def query(q: String): String
  }
  trait Logger {
    def log(l: String): Unit
  }
  trait RequiredServices {
    def makeDatabaseConnection: Connection
    def logger: Logger
  }
  trait TestServices extends RequiredServices {
    def makeDatabaseConnection = new Connection { def query(q: String) = "test" }
    def logger = new Logger { def log(l: String) = println(l) }
  }
  trait ProductFinder { this: RequiredServices =>
    def findProduct(productId: String) = {
      val c = makeDatabaseConnection
      c.query(productId)
      logger.log("querying database..")
    }
  }
  object FinderSystem extends ProductFinder with TestServices  

我的问题特别与代码的以下部分有关:

this: RequiredServices =>
        def findProduct(productId: String) = {
...

上面的Scala构造的名称是什么?即 this: RequiredServices =>

预先感谢您的答复。

名称为 self type 注释。它在Scala语言规范的§5.1(模板)中进行了解释,如下:

模板语句的序列可以以形式的参数定义和箭头(例如 x =>,或 x:t =>。如果给出了形式参数,则可以用作模板正文中参考 this 的别名。如果形式参数带有类型 t ,则此定义会影响基础类或对象的 self type s ,如下所示:令 c 为定义模板的类,特质或对象的类型。如果为形式的自我参数提供了类型 t ,则 s t c 的最大下限。如果没有给出类型 t ,则 s 只是 c 。在模板中,的类型假定为 s

类或对象的自我类型必须符合模板 t 的所有类的自我类型。

第二种形式的自我类型注释仅读取以下: s =>。它为> 开出类型 s ,而无需引入别名名称。

最新更新