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

不想你离开。 提交于 2019-12-02 05:57:12

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/11054299/can-we-assign-change-traits-to-the-scala-class-during-runtime-how-any-sampl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!