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

前端 未结 2 996
南方客
南方客 2021-01-22 19:07

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

2条回答
  •  执念已碎
    2021-01-22 19:36

    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.

提交回复
热议问题