Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>An existing runtime object in the JVM has a certain size on the heap. Adding a trait to it would mean altering its size on the heap, and changing its signature.</p> <p>So the only way to go would be to do some kind of transformation at compile time.</p> <p>Mixin composition in Scala occurs at compile time. What compiler could potentially do is create a wrapper B around an existing object A with the same type that simply forwards all calls to the existing object A, and then mix in a trait T to B. This, however, is not implemented. It is questionable when this would be possible, since the object A could be an instance of a final class, which cannot be extended.</p> <p>In summary, mixin composition is not possible on existing object instances.</p> <p>UPDATED:</p> <p>Related to the smart solution proposed by Googol Shan, and generalizing it to work with any trait, this is as far as I got. The idea is to extract the common mixin functionality in the <code>DynamicMixinCompanion</code> trait. The client should then create a companion object extending <code>DynamicMixinCompanion</code> for each trait he wants to have the dynamic mixin functionality for. This companion object requires defining the anonymous trait object gets created (<code>::</code>).</p> <pre><code>trait DynamicMixinCompanion[TT] { implicit def baseObject[OT](o: Mixin[OT]): OT = o.obj def ::[OT](o: OT): Mixin[OT] with TT class Mixin[OT] protected[DynamicMixinCompanion](val obj: OT) } trait OtherTrait { def traitOperation = println("any trait") } object OtherTrait extends DynamicMixinCompanion[OtherTrait] { def ::[T](o: T) = new Mixin(o) with OtherTrait } object Main { def main(args: Array[String]) { val a = "some string" val m = a :: OtherTrait m.traitOperation println(m.length) } } </code></pre>
    singulars
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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