在akka Actors中堆叠多个特征

Adr*_*ian 10 scala traits actor akka

我正在创建扩展Actor的多个特征.然后我想创建一个使用其中一些特征的actor类.但是,我不确定如何在Actor类的receive方法中组合所有traits的receive方法.

性状:

 trait ServerLocatorTrait extends Actor {
    def receive() = {
      case "s" => println("I'm server ")
    }
  }

  trait ServiceRegistrationTrait extends Actor {
    def receive() = {
      case "r" => println("I'm registration ")
    }
  }
Run Code Online (Sandbox Code Playgroud)

演员:

class FinalActor extends Actor with ServiceRegistrationTrait with ServerLocatorTrait {
  override def receive = {
     super.receive orElse ??? <--- what to put here
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我送"r",并"s"FinalActor它去只有ServerLocatorTrait-这是最后的特质补充说.所以现在它的工作方式是它认为超级最后添加的特性,所以在这种情况下ServerLocatorTrait

问题:
如何组合所有特征的接收方法FinalActor

PS - 我见过演员的react例子:http://www.kotancode.com/2011/07/19/traits-multiple-inheritance-and-actors-in-scala/ 但这不是我需要的

Mar*_*ila 17

我不知道你是否能结合接收方法,因为这将涉及调用超级的超级获得ServiceRegistrationreceive方法.这也很令人困惑.

另一种receive方法是在特征中给出方法的不同名称.

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()

}
Run Code Online (Sandbox Code Playgroud)

您仍然可以使用初始方法,但必须super.receive为每个混合特征链接.

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
Run Code Online (Sandbox Code Playgroud)

后一种解决方案对我来说非常难看.

有关此主题的更详细讨论,请参阅以下链接:

使用PartialFunction链扩展Actor