Search code examples
design-patternsscalastrategy-pattern

Can we assign / change traits to the scala class during runtime? How - any sample code? Like Strategy Pattern (of Gang of four Design Pattern)


To explain my question:

Class : Toy

Trait1: Speak like Male

Trait2: Speak like Female

Can I change the behavior (traits) of Toy during runtime so sometimes the same object speaks like male and sometimes the same object speaks like female?

I want to change the speaking behavior at runtime.


Solution

  • Scala really doesn't do that. There's Kevin Wright's autoproxy plugin which can do it, and you can instantiate and object with either trait, without that trait being part of the base class.

    I personally think that trying to accomplish things that way is to go against the grain of Scala: hard and prone to getting stuck. It is better to design a solution that doesn't require such things -- in fact, Scala grain tends much more to the functional, which put focus on everything being immutable, and replacing one object with a new one as a result of computation.