假设我有两个特征,其中一个是另一个工厂:
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
可以包含BaseT
类型的字段,但是它需要手动代理所有必要的方法和字段,这在我看来是违反DRY原则的。怎么解决?
答案 0 :(得分:0)
如何在ExtendBaseTBuilder中创建ExtendBaseT实例
trait ExtendBaseTBuilder { self : BaseTBuilder =>
def build: ExtendBaseT = {
new ExtendBaseT {
val someNewCoolField: Int = 3
}
}
}