10

我正在创建多个扩展 Actor 的特征。然后我想创建一个使用这些特征的演员类。但是,我不确定如何在 Actor 类的接收方法中组合来自所有特征的接收方法。

性状:

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

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

演员:

class FinalActor extends Actor with ServiceRegistrationTrait with ServerLocatorTrait {
  override def receive = {
     super.receive orElse ??? <--- what to put here
  }
}

现在,如果我发送"r"并且它只进入"s"-这是添加的最后一个特征。所以现在它的工作方式是它认为 super 是添加的最后一个特征,所以在这种情况下FinalActorServerLocatorTraitServerLocatorTrait

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

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

4

1 回答 1

17

我不确定您是否可以组合接收方法,因为这将涉及调用 super 的 super 来获取ServiceRegistration'receive方法。这也会非常混乱。

另一种方法是为特征中的方法赋予不同的名称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()

}

您仍然可以使用初始方法,但您必须链接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

后一种解决方案对我来说看起来很丑陋。

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

使用 PartialFunction 链接扩展 Actor

于 2013-08-27T15:15:30.647 回答