Search code examples
scalasyntax

Type declaration for this in trait body


In project I work on I found following code:

trait Trait1 {
  this: Actor with Reader with Writer =>

  import ProjectDefaultLib._

  val var1: String

  // rest of the code
}

I couldn't find what this: Actor with Reader with Writer => notation means. Please explain.


Solution

  • That's a self-type annotation.

    From the Tour of Scala:

    Self-types are a way to declare that a trait must be mixed into another trait, even though it doesn’t directly extend it. That makes the members of the dependency available without imports.

    You can see a more complex example of how this is used here in the Scala Book.

    This answer goes more in depth with regards on when and how to use self-types instead of direct extension.