scalaself-type

Explanation of Scala construct


I am busy with a major refactoring task on some legacy Scala/Akka code, and am being haunted by a construct that I am unable to explain, which is hampering my effort:

trait PerRequestCreator {
  this: Actor =>
  def perRequest(<some_params>): ActorRef = { body of function }
}

Which is then used as such:

class SomeActor extends PerRequestCreator with Actor {
  def processRequest: Route = {
    perRequest(<some_params_passed>)
  }
}

I am having trouble understanding the this: Actor => ... part of the trait.


Solution

  • It's called self-type, and it expresses a requirement for the PerRequestCreator to be mixed in into something that extends Actor.

    It's useful because now you can use anything defined in Actor inside the definition of PerRequestCreator and the compiler will check that you can only extend PerRequestCreator if you also extend Actor.

    Example:

    class SomeClass extends PerRequestCreator            // this won't compile
    class SomeClass extends PerRequestCreator with Actor // this is ok
    

    You can read more about it here: https://docs.scala-lang.org/tour/self-types.html