2011-03-21 49 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

相關問題