O'Reilly logo

Programming Scala by Alex Payne, Dean Wampler

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Self-Type Annotations

You can use this in a method to refer to the enclosing type, which is useful for referencing a member of the type. Using this is not usually necessary for this purpose, but it’s useful occasionally for disambiguating a reference when several values are in scope with the same name. By default, the type of this is the same as the enclosing type, but this is not really essential.

Self-type annotations let you specify additional type expectations for this, and they can be used to create aliases for this. Let’s consider the latter case first:

// code-examples/TypeSystem/selftype/this-alias-script.scala

class C1 { self =>
  def talk(message: String) = println("C1.talk: " + message)
  class C2 {
    class C3 {
      def talk(message: String) = self.talk("C3.talk: " + message)
    }
    val c3 = new C3
  }
  val c2 = new C2
}
val c1 = new C1
c1.talk("Hello")
c1.c2.c3.talk("World")

It prints the following:

C1.talk: Hello
C1.talk: C3.talk: World

We give the outer scope (C1) this the alias self, so we can easily refer to it in C3. We could use self within any method inside the body of C1 or its nested types. Note that the name self is arbitrary, but it is somewhat conventional. In fact, you could say this =>, but it would be completely redundant.

If the self-type annotation has types in the annotation, we get some very different benefits:

// code-examples/TypeSystem/selftype/selftype-script.scala

trait Persistence {
  def startPersistence: Unit
}

trait Midtier {
  def startMidtier: Unit
}

trait UI {
  def ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required