stacking multiple traits in akka Actors

后端 未结 1 1811
醉梦人生
醉梦人生 2021-02-06 01:49

I\'m creating multiple traits which extend Actor. Then I want to create an actor class which uses some of these traits. However, I\'m not sure how to combine the receive methods

1条回答
  •  逝去的感伤
    2021-02-06 02:39

    I'm not sure if you can combine the receive methods, since that would involve calling the super's super to obtain the ServiceRegistration's receive method. It would also be very confusing.

    Another way would be to give different names to the receive method in the traits.

    trait ServerLocatorTrait extends Actor {
      def handleLocation: Receive = {
        case "s" => println("I'm server ")
      }
    }
    
    trait ServiceRegistrationTrait extends Actor {
      def handleRegistration: Receive = {
        case "r" => println("I'm registration ")
      }
    }
    
    class FinalActor extends Actor with ServiceRegistrationTrait with ServerLocatorTrait {
      def receive = handleLocation orElse handleRegistration
    }
    
    object Main extends App {
    
      val sys = ActorSystem()
    
      val actor = sys.actorOf(Props(new FinalActor))
    
      actor ! "s"
      actor ! "r"
    
      sys.shutdown()
    
    }
    

    You can still use you initial approach, but you must chain the super.receive for each mixed trait.

    trait IgnoreAll extends Actor {
      def receive: Receive = Map()
    }
    
    trait ServerLocatorTrait extends Actor {
      abstract override def receive = ({
        case "s" => println("I'm server ")
      }: Receive) orElse super.receive
    }
    
    trait ServiceRegistrationTrait extends Actor {
      abstract override def receive = ({
        case "r" => println("I'm registration ")
      }: Receive) orElse super.receive
    }
    
    class FinalActor extends IgnoreAll with ServiceRegistrationTrait with ServerLocatorTrait
    

    The latter solution looks pretty ugly to me.

    Please see the below link for a more detailed discussion on the subject:

    Extending Actors using PartialFunction chaining

    0 讨论(0)
提交回复
热议问题