给定一个行为实例,我可以向它应用消息以创建新行为吗

Given an instance of a behavior can I apply a message to it to create a new behavior

我有一个场景,我正在处理收到消息时需要一些额外信息的通用行为:

case class A(count: Int)

type MyBehavior[T] = Behavior[(A, T)]

处理这些额外信息的代码可能如下所示:

case class B(str: String)

def active(b: B): MyBehavior[B] = Behaviors.receiveMessage {
  case (a, b) =>
    active(b.copy(str = a.count.toString)
}

然后我有一个函数来一般地处理这个行为。但是给出了对行为的引用,我不知道如何向它应用消息来创建新行为:

def f[T](a: A, behavior: MyBehavior[T])(implicit ct: ClassTag[T]): Behavior[T] =
    Behaviors.receiveMessage {
        case t: T =>
            val newBehavior: MyBehavior[T] = ???   // Can I pass a and t?
            f(a.copy(count = a.count + 1), newBehavior)
}

有没有办法将消息应用到行为以创建新行为?

您可以使用 context 生成一个新演员,并从您当前的演员向 if 发送消息。这样你就可以在该演员完成的动作之前“添加”一些逻辑。

Behaviors.setup { context =>

  def f[T](implicit ct: ClassTag[T]): Behavior[(A, T)] =
    Behaviors.receiveMessage {
      case (a: A, t: T) =>
        val newA = a.copy(count = a.count + 1)
        val newActor = context.spawn(f[T])
        newActor ! (newA, t)
    }
}

您的代码中缺少重要的东西 - 行为是演员的秘诀,但它不是演员本身.您必须使用 ActorSystem(behavior, actorSystemName)(进入整个系统)或通过 context.spawn(behavior) 实例化它。否则你的递归调用将只是递归调用,而不是从 actor 向新生成的 actor 发送消息。