scalapath-dependent-type

What is the use of `*.this` in Scala?


class S {
  case class A(a: Int)
}

abstract class R(val s: S) {
  type T1 = R.this.s.A
  type T2 = s.A
  implicitly[T1 =:= T2] // compiles

  type T3 = R.this.type
  type T4 = this.type
  implicitly[T3 =:= T4] // compiles

  val v1 = R.this //  v1 == `this`
  val v2 = R.this.s // v2 == `s`
}

Looks like the .this part has no effect whatsoever. To make a concrete question: When do you use the .this ?


Solution

  • It matters for inner classes. E.g.

    class Outer(val x: Int) {
      class Inner(val x: Int) {
        def outer_this = Outer.this.x
        def inner_this = this.x // or just x
      }
    }
    
    val outer = new Outer(0)
    val inner = new outer.Inner(1)
    println(inner.outer_this) // 0
    println(inner.inner_this) // 1
    

    Each Outer.Inner instances "belongs to" a specific Outer instance, and can refer to that instance as Outer.this. By itself x in Inner refers to its own property, so if you need the enclosing instance's x property, you write Outer.this.x.