假设我有两个特征,其中一个是另一个工厂:
trait BaseT {
val name: String
def introduceYourself() = println("Hi, I am " +name)
// some other members ...
}
trait BaseTBuilder {
def build: BaseT
}
现在,我想扩展 BaseT:
trait ExtendedT extends BaseT {
val someNewCoolField: Int
override def introduceYourself() = {
super.introduceYourself()
println(someNewCoolField)
}
// some other extra fields
假设我知道如何初始化新字段,但我想BaseTBuilder
用于初始化超类成员。是否有可能创建一个能够以ExtendedT
某种方式实例化的特征?这种方法显然失败了:
trait ExtendedTBuilder { self: TBuilder =>
def build: ExtendedT = {
val base = self.build()
val extended = base.asInstanceOf[ExtendedT] // this cannot work
extended.someNewCoolField = 4 // this cannot work either, assignment to val
extended
}
def buildDifferently: ExtendedT = {
new ExtendedT(4) // this fails, we don't know anything about constructors of ExtendedT
}
def build3: ExtendedT = {
self.build() with {someNewCoolField=5} //that would be cool, but it cannot work either
}
}
我希望有这样一组特征(或对象),当有人提供具体实现时BaseT
,BaseTBuilder
我可以ExtendedT
通过编写来实例化:
val extendedBuilder = new ConcreteBaseTBuilder with ExtendedTBuilder
val e: ExtendedT = extendedBuilder.build
ExtendedT
可以包含 type 的字段BaseT
,但随后需要手动代理所有必要的方法和字段,我认为这违反了 DRY 原则。如何解决?