Note that there are some explanatory texts on larger screens.

plurals
  1. POScala: subclassing with factories
    primarykey
    data
    text
    <p>Let's say I've got two traits, one of them being a factory for another:</p> <pre><code>trait BaseT { val name: String def introduceYourself() = println("Hi, I am " +name) // some other members ... } trait BaseTBuilder { def build: BaseT } </code></pre> <p>Now, I want to extend BaseT:</p> <pre><code>trait ExtendedT extends BaseT { val someNewCoolField: Int override def introduceYourself() = { super.introduceYourself() println(someNewCoolField) } // some other extra fields </code></pre> <p>Let's say I know how to initialize the new fields, but I'd like to use <code>BaseTBuilder</code> for initializing superclass members. Is there a possibility to create a trait that would be able to instantiate <code>ExtendedT</code> somehow? This approach obviously fails:</p> <pre><code>trait ExtendedTBuilder { self: TBuilder =&gt; 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 } } </code></pre> <p>I'd like to have such a set of traits (or objects) that when someone supplies concrete implementation of <code>BaseT</code> and <code>BaseTBuilder</code> I could instantiantiate <code>ExtendedT</code> by writing:</p> <pre><code>val extendedBuilder = new ConcreteBaseTBuilder with ExtendedTBuilder val e: ExtendedT = extendedBuilder.build </code></pre> <p><code>ExtendedT</code> could contain a field of type <code>BaseT</code>, but then it would require manually proxying all the necessary methods and fields, which is in my opinion a violation of DRY principle. How to solve that? </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload