我想实现以下代码,但自类型行无法编译。是我的语法有误还是这根本不可能?
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 { ...
我想实现以下代码,但自类型行无法编译。是我的语法有误还是这根本不可能?
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 { ...
你可以拥有一个单一的自类型,它是一个复合类型。
试试这个:
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
使用结构类型,您可以通过一个特征来实现:
trait C {
self: { def aValue: Int
def bValue: Int } =>
def total = aValue + bValue
}
class ABC extends C {
def aValue = 1
def bValue = 1
}
使用了反射。
但是,首先你不应该过度使用自类型,因为这违反了最小权力原则。
可以通过扩展其他特质简单地添加问题中的方法:
trait C extends A with B{
def total = aValue + bValue
}
trait C {
def aValue: Int
def bValue: Int
def total = aValue + bValue
}
何时使用自类型?
自类型通常与类一起使用。这是 trait 要求成为所需类的子类的好方法。
还有一个使用自类型与 triat 的好方法:当您想要使用多重继承来操作类初始化顺序时。