为什么我不能指定特征的子类?

时间:2011-03-21 23:36:28

标签: scala traits

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 = B@2e9c76

scala> res0.t
res1: Int = 1

我认为当你编写trait T extends A时,它会使你只能将特征T放在A的子类上。那我为什么可以把它放在B上呢?这只适用于你混入的时候吗?为什么在宣布课时不可能这样做?

3 个答案:

答案 0 :(得分:5)

  

“它使得你只能放入特质   T是一个类,是A“

的子类

您想要的功能是自我类型注释。另请参阅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 }

答案 1 :(得分:0)

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

答案 2 :(得分:0)

你不能做的是:

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相同。