简体   繁体   中英

About using this.type in scala

I defined two classes:

class A { def method1 = this }
class B extends A { def method2 = this }

val b = new B

Then I checked the type of b.method1:

scala> b.method1.getClass
res29: Class[_ <: A] = class B

In this case, I cannot use b.method1.method2 :

scala> b.method1.method2
<console>:11: error: value method2 is not a member of A
              b.method1.method2

So I have to define A and B like this:

class A { def method1: this.type = this } 
class B extends A { def method2: this.type = this } 

val b = new B

Now I check the type of b.method1 :

scala> b.method1.getClass
res31: Class[_ <: B] = class B

Here b.method1.method2 works:

scala> b.method1.method2
res32: b.type = B@4ff3ac

My question here is what does it mean by saying Class[_ <: A] = class B and Class[_ <: B] = class B ? And why does the first doesn't work as Class[_ <: A] = class B seems to say that it's also class B?

Let's split the expression Class[_ <: A] = class B . The first part, Class[_ <: A] tells you what the compiler knows at compile time, that b.method1.getClass returns something of type Class[_ <: A] . The second part, class B mentions that you have a class B as value, but the compiler doesn't know that. That's runtime information.

this.type specializes the method for subclasses, where the type inferred from a plain this doesn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM