Question

I have a question regarding the following code:

  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  

My question especially relates to the following portion of code:

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

What is the name of the Scala construct of the above? i.e. the this: RequiredServices =>

Thanks in advance for your replies.

Was it helpful?

Solution

The name is self type annotation. It is explained in §5.1 (Templates) of the Scala Language Specification, as follows:

The sequence of template statements may be prefixed with a formal parameter definition and an arrow, e.g. x =>, or x:T =>. If a formal parameter is given, it can be used as an alias for the reference this throughout the body of the template. If the formal parameter comes with a type T, this definition affects the self type S of the underlying class or object as follows: Let C be the type of the class or trait or object defining the template. If a type T is given for the formal self parameter, S is the greatest lower bound of T and C. If no type T is given, S is just C. Inside the template, the type of this is assumed to be S.

The self type of a class or object must conform to the self types of all classes which are inherited by the template t.

A second form of self type annotation reads just this: S =>. It prescribes the type S for this without introducing an alias name for it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top