1

假设我有两个特征,其中一个是另一个工厂:

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
  }
}

我希望有这样一组特征(或对象),当有人提供具体实现时BaseTBaseTBuilder我可以ExtendedT通过编写来实例化:

val extendedBuilder = new ConcreteBaseTBuilder with ExtendedTBuilder
val e: ExtendedT = extendedBuilder.build

ExtendedT可以包含 type 的字段BaseT,但随后需要手动代理所有必要的方法和字段,我认为这违反了 DRY 原则。如何解决?

4

1 回答 1

0

如何在您的 ExtendBaseTBuilder 中创建 ExtendBaseT 实例

trait ExtendBaseTBuilder { self : BaseTBuilder =>
  def build: ExtendBaseT = {
    new ExtendBaseT {
      val someNewCoolField: Int = 3
    }
  }

}
于 2013-10-21T14:02:33.533 回答