An existing run-time object in the JVM has a specific size on the heap. Adding a tag to it would mean changing its size on the heap and changing its signature.
So the only way to go is to do some kind of conversion at compile time.
The composition of the mixture in Scala occurs at compile time. The compiler could potentially create a wrapper B around an existing object A with the same type, which simply redirects all calls to the existing object A, and then mixes with the tag T from B. This, however, is not implemented. This may be a question when it would be possible, since object A may be an instance of a finite class that cannot be extended.
Therefore, mixin composition is not possible in existing object instances.
UPDATED:
In connection with the smart solution proposed by Gogol-Shan, and summarizing it to work with any sign, this is, as I understand it. The idea is to extract the general mixin functionality into the DynamicMixinCompanion . Then, the client must create a companion object that extends the DynamicMixinCompanion for each attribute for which he wants to have dynamic mixin functionality. This companion object requires the definition of creating an anonymous object object ( :: .
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) } }
axel22 Oct 08 2018-10-10 18:43
source share