2

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.

Optimight
  • 2,989
  • 6
  • 30
  • 48

2 Answers2

4
sealed trait Speaker
case object Male extends Speaker
case object Female extends Speaker

class Toy(name: String, speaks: Speaker = Male) { 
  def speak = speaks match {
    case Male   => "ugh"
    case Female => "What time do you call this?"
  }
}

Then

barbie = ken.copy(speaks = Female)

You cannot change the traits which an object extends at runtime, because a trait is mixed in to create a class (in a .class file). A given object has exactly one class and this can never be changed.

oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
  • Sir, thank you very much for your input. Will put your code into practice and will try to understand it. I am still unclear that how to make the same barbie speak like male? Please note that I am just a scala beginner and has very little programming experience. – Optimight Jun 15 '12 at 17:21
  • In that case, just make the `val` a `var` (`case class` values are `val`s by default). Try `Toy(var speaks: Speaker)` and then `ken.speaks = Female` – oxbow_lakes Jun 15 '12 at 17:48
2

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.

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
  • Sir, Agreed and accepted that Scala tends to the functional, which puts focus on being immutable, and replacing one object with a new one as a result of computation. Query: In a real world, player (object) is changing his behavior from defensive, aggressive, supportive etc., but his life continues. If the player is put into software, whenever his behavior changes, we have to program in a manner that existing player (object) is replaced with new player with current behavior, right? How to program this scenario in Scala. (java scenario : interfaces can be changed in runtime.) – Optimight Jun 16 '12 at 00:28
  • Sir, I read The Autoproxy Plugin - Part I & II. Is it a functionality like in java Annotation Processing Tool? Does Scala have Annotation Processing Tools? – Optimight Jun 16 '12 at 01:34
  • @Optimight Scala does not have annotation processing tools. It is a compiler plugin, meaning it is an extension of the compiler itself. – Daniel C. Sobral Jun 17 '12 at 01:24