2011-03-21 38 views
0
scala> class A 
defined class A 

scala> trait T extends A { val t = 1 } 
defined trait T 

//why can I do this? 
scala> class B extends T 
defined class B 

scala> new B 
res0: B = [email protected] 

scala> res0.t 
res1: Int = 1 

我认为,当你写trait T extends A,这使得它,所以你只能把特质T上一类是A一个子类。为什么我可以把它放在B上呢?这只适用于混合时的情况吗?为什么在宣布课程时这是不可能的?为什么我不能指定特征的子类?

回答

5

“这使得它,所以你只能把特质 T于一类,它是的一个子类”你想

的特点是自类型的注释。另请参阅Daniel Sobral对此问题的回答:What is the difference between self-types and trait subclasses? - >查找依赖注入和饼状模式的链接。

trait A { def t: Int } 
trait B { 
    this: A => // requires that a concrete implementation mixes in from A 
    def t2: Int = t // ...and therefore we can safely access t from A 
} 

// strangely this doesn't work (why??) 
def test(b: B): Int = b.t 

// however this does 
def test2(b: B): Int = b.t2 

// this doesn't work (as expected) 
class C extends B 

// and this conforms to the self-type 
class D extends B with A { def t = 1 } 
0

你简直困惑于什么是特质。说class B extends T只是意味着你将特征的功能“混合”到B的类定义中。因此,在T中定义的所有东西或它的父类和特征都可以在B中使用。

+0

对,但'特质T扩展A'应该只允许你将特性混入到A类中。如果你尝试用'T来新B' - 它不会让你这样做。 – ryeguy 2011-03-22 13:17:21

+0

不,“特质T扩展A”不*应该只允许你将特征混入类A中。它将类A的功能添加到特征T中。因此T具有功能(方法和字段)和A中定义的任何东西。当你说'class B extends T'时,你引入了T *和* A中的所有东西。 – 2011-03-22 19:36:25

+0

@ThomasLockney你应该看看http:// stackoverflow。 com/questions/12854941/why-can-a-scala-trait-extend-a-class 我认为这就是reguy所指的 – hencrice 2015-08-02 22:31:01

0

什么是'做T是:

scala> class A2 
defined class A2 

scala> class B extends A2 with T 
<console>:8: error: illegal inheritance; superclass A2 
is not a subclass of the superclass A 
of the mixin trait T 
     class B extends A2 with T 
          ^

其实,写class B extends T是一样的书写class B extends A with T

相关问题