Scala 有多种自我类型吗?
我想执行以下操作,但self-type行无法编译。我的语法是错误的还是根本不可能Scala 有多种自我类型吗?,scala,Scala,我想执行以下操作,但self-type行无法编译。我的语法是错误的还是根本不可能 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
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
}
使用反射
但是,首先,你不应该过度使用自我类型,因为
通过扩展其他tait,可以简单地添加问题中的方法:
trait C extends A with B{
def total = aValue + bValue
}
或者显式键入两种方法:
trait C {
def aValue: Int
def bValue: Int
def total = aValue + bValue
}
在哪里使用自我类型?
Self类型通常与类一起使用。这是trait要求成为所需类的子类的好方法
self-type在triat中还有一个很好的用途:当您想用多重继承操作类初始化的顺序时