我想根据个别特征提供的项目建立一个列表。为此,我可以使用可堆叠特征来做到这一点:
trait StackableBuilder {
def build: Seq[String] = Seq.empty
def buildAll: Seq[String] = build
}
trait BuildA extends StackableBuilder {
abstract override def build = super.build :+ "A"
}
trait BuildB extends StackableBuilder{
abstract override def build = super.build :+ "B"
}
object AB extends StackableBuilder with BuildA with BuildB
println(AB.buildAll)
尽管如此,我想稍微改进一下,以便每个部分构建器都不必重复super.build
调用,这有点像:
trait StackableBuilder {
def build: String
def buildAll: Seq[String] = ???
}
trait BuildA extends StackableBuilder {
def build = "A"
}
trait BuildB extends StackableBuilder {
def build = "B"
}
object AB extends StackableBuilder with BuildA with BuildB
println(AB.buildAll)
现在这不编译,错误是“对象AB继承冲突的成员”,即使它确实存在,仍然需要填充部分???
。
是否有可能以某种方式定义可堆叠的特征,以便使用超级调用的堆叠不必由单个特征完成,可能会引入一些辅助特征和方法,可能有点像How to call super method when overriding a method through a trait?
答案 0 :(得分:0)
一项改进是将默认功能分离到另一个trait
,然后通过强制他使用super
来提醒用户abstract override
呼叫override
。使用普通 trait StackableBuilder {
def build: Seq[String]
}
trait StackableBuilderRoot extends StackableBuilder {
override def build: Seq[String] = Seq.empty
def buildAll: Seq[String] = build
}
trait BuildA extends StackableBuilder {
abstract override def build = super.build :+ "A"
}
trait BuildB extends StackableBuilder{
abstract override def build = super.build :+ "B"
}
object AB extends StackableBuilderRoot with BuildA with BuildB
println(AB.buildAll)
是可能的,而问题中的代码没有错误。
read.table