Scala 阿克卡。有没有办法在两个接收器之间共享代码?

Scala 阿克卡。有没有办法在两个接收器之间共享代码?,scala,akka,Scala,Akka,假设我有几个接收,并使用been()unbecome()在它们之间切换。所有接收都有一些通用的消息处理。像这样: class Test extends Actor { override def receive: Receive = first def first: Receive = { case "common" => // how to share? println("common stuff") case "second" =>

假设我有几个接收,并使用been()unbecome()在它们之间切换。所有接收都有一些通用的消息处理。像这样:

class Test extends Actor {

  override def receive: Receive = first

  def first: Receive = {
    case "common" => // how to share?
      println("common stuff")
    case "second" =>
      println("move to second")
      context.become(second)
  }

  def second: Receive = {
    case "common" =>  // how to share?
      println("common stuff")
    case "first" =>
      println("move to first")
      context.become(first)
  }

}
现在我看到两种方式:

  • “通用”和“通用”上的重复模式匹配 用handleCommon()之类的函数处理它
  • 合并接收类似 这个,但我觉得不对
下面是第二个示例:

class Test extends Actor {

      override def receive: Receive = merge(common, first)

      def common: Receive = {
        case "common" =>
          println("common stuff")
      }

      def first: Receive = {
        case "second" =>
          println("move to second")
          context.become(merge(common, second))
      }

      def second: Receive = {
        case "first" =>
          println("move to first")
          context.become(merge(common, first))
      }

      private def merge(functions: Receive*): Receive = {
        case any =>
          val fOpt = functions find (_.isDefinedAt(any))
          if (fOpt.isDefined) {
            fOpt foreach (f => f(any))
          } else {
            unhandled(any)
          }
      }
    }

我相信一定有更好的方法来做到这一点。有吗?

您可以使用
orElse

def common: Receive = {
  case "common" =>
    println("common stuff")
}

def first: Receive = ({
  case "second" =>
    println("move to second")
    context.become(second)
}: Receive) orElse common

def second: Receive = ({
  case "first" =>
    println("move to first")
    context.become(first)
}: Receive) orElse common

请注意,您必须在表达式末尾显式注释类型,否则scala将推断
Function1
,而不是
Receive

,我想最好使用
val
定义
common
,以便更容易看到它只是一个部分函数,仅用于mix inI,不要认为它太重要,最后,即使它是一个val,它也是一个函数,所以每次调用时都会对它求值,通常我会将这种共享接收设置为私有。这正是我试图编辑我的评论的地方。我想说的是
private val
,而不是
val