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

scala> res0.t
res1: Int = 1

我认为当您编写时trait T extends A,它使您只能将 traitT放在作为A. 那我为什么能装B?这只适用于你混合它的时候吗?为什么在声明类时这是不可能的?

4

3 回答 3

5

“它做到了,所以你只能将特征 T 放在作为 A 子类的类上”

您想要的功能是自类型注释。另请参阅 Daniel Sobral 对此问题的回答:自我类型和特质子类之间有什么区别?--> 寻找依赖注入和蛋糕模式的链接。

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 }
于 2011-03-22T00:06:59.007 回答
0

您只是对特征是什么感到困惑。简单地说class B extends T,意味着您将特征的功能“混合”到 B 的类定义中。因此,在 T 中定义的所有内容或其父类和特征都在 B 中可用。

于 2011-03-22T07:41:32.397 回答
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

于 2011-04-16T16:32:58.653 回答