2015年12月16日星期三

Scala中this.type的使用

一直有一个疑问没搞懂,有必要在这里发上一帖,参见我提的问题和回答:链接

问题如下:
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?

Reactormonk很好地解答了我的疑问:
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 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 thisdoesn't.

没有评论:

发表评论