Tom
Tom

Reputation: 6332

Can't understand path dependent type

For a class C, you can use the familiar this inside the body to refer to the current instance, but this is actually a shorthand for C.this in Scala:

class C {
   var x = "1"
   def setX1(x:String) = this.x = x
   def setX2(x:String) = C.this.x = x
}

I just can't understand C.this, C is a class, I can't understand why we use dot between C and this as shown in C.this?

Upvotes: 2

Views: 56

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149518

I can't understand why we use dot between C and this as shown in C.this

Using the class name before this is called a Qualified this in Java (see Using "this" with class name) and is similar in Scala. You use it when you want to reference an outer class from an inner class. Let's assume for example that you had a method declaration in your C class where you wanted to call this and mean "the this reference of C:

class C {
  val func = new Function0[Unit] {
    override def apply(): Unit = println(this.getClass) 
  }
}

new C().func()

Yields:

class A$A150$A$A150$C$$anon$1

You see the anon$1 at the end of the getClass name? It's because inside the function instance this this is actually of the function class. But, we actually wanted to reference the this type of C instead. For that, you do:

class C {
  val func = new Function0[Unit] {
    override def apply(): Unit = println(C.this.getClass)
  }
}

new C().func()

Yields:

class A$A152$A$A152$C

Notice the C at the end instead of anon$1.

Upvotes: 1

Related Questions