2010-12-04 45 views
37

我想要做以下事情,但自行式行不能編譯。我有這個語法錯誤嗎?或者這僅僅是不可能的?是否有多種自我類型?

trait A { 
    def aValue = 1 
} 
trait B { 
    def bValue = 1 
} 
trait C { 
    a : A, b : B => 
    def total = a.aValue + b.bValue 
} 

class T extends C with A with B { ... 

回答

65

您可以擁有一個複合類型的自我類型。

試試這個:

trait A { 
    def aValue = 1 
} 
trait B { 
    def bValue = 1 
} 
trait C { 
    self: A with B => 
    def total = aValue + bValue 
} 

class ABC extends A with B with C 
2

隨着一個特點你可以結構型做到這一點:使用

trait C { 
    self: { def aValue: Int 
      def bValue: Int } => 

    def total = aValue + bValue 
} 

class ABC extends C { 
    def aValue = 1 
    def bValue = 1 
} 

反思。

但是,首先你不應該過度使用自我類型,因爲principle of least power。從問題

方法可以簡單地通過擴展其他泰特加入:

trait C extends A with B{ 
    def total = aValue + bValue 
} 

或鍵入這兩種方法明確:

trait C { 
    def aValue: Int 
    def bValue: Int 

    def total = aValue + bValue 
} 

凡使用自助類型?

自我類型通常與類一起使用。這是特質要求成爲所需班級的一個子類的好方法。

還有一個很好用的自我類型與triats:當你想操縱多繼承類初始化的順序。