2010-12-04 47 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:当你想操纵多继承类初始化的顺序。