【问题标题】:Why Receive Actor method in akka behaves like a val?为什么 akka 中的 Receive Actor 方法的行为类似于 val?
【发布时间】:2016-12-31 07:39:57
【问题描述】:

我想知道为什么这段代码中 akka Actor 的接收方法表现得像一个 val ?

import akka.actor.{ ActorRef, ActorSystem, Props, Actor }
import scala.concurrent.duration._


// Define Actor Messages
case class WhoToGreet(who: String)


// Define Greeter Actor
class Greeter extends Actor {
  def receive = {
    println("in receive")
    receiveHandler
  }


  def receiveHandler: Receive = {
    case WhoToGreet(who) => println(s"Hello $who")
  }
}

object HelloAkkaScala extends App {

  // Create the 'hello akka' actor system
  val system = ActorSystem("Hello-Akka")

  // Create the 'greeter' actor
  val greeter = system.actorOf(Props[Greeter], "greeter")

  // Send WhoToGreet Message to actor
  greeter ! WhoToGreet("Akka")

  greeter ! WhoToGreet("Akka")

  greeter ! WhoToGreet("Akka")


  //shutdown actorsystem
  system.terminate()

}

输出:

in receive
Hello Akka
Hello Akka
Hello Akka

当它应该是:

in receive
Hello Akka
in receive
Hello Akka
in receive
Hello Akka

而接收是一个定义。

关于这种行为的任何想法,为什么这里的 def 像 val 一样计算?

【问题讨论】:

    标签: scala akka


    【解决方案1】:

    receive 返回一个 PartialFunction[Any, Unit],并将 PartialFunction 作为 Actors 行为播种(可以通过 context.become/unbecome 进行更改)。

    它被认为是 val 的原因是 PartialFunction 实例在更改之前被重复使用。

    【讨论】:

    • 谢谢,但是为什么在这个 code 中它的行为就像一个 def ?
    • 您链接的代码与PartialFunctions完全无关,您可以通过将返回类型更改为Unit来证明这一点。您的方法在 PartialFunction 之外执行副作用 (printlns)。 Akka 调用(缓存的)PartialFunction。
    • 请看一下上面的代码,我把Partial类型改成了:type Partial = PartialFunction[Any, Unit] 我看不出区别
    • 好像有误会,我不是说改成PartialFunction[Any, Unit],是说改成Unit。
    • 我仍然没有看到 Actor Class 中的 receive 方法和我的示例中的 hello 方法之间的区别,它们都返回一个 PartialFunction[Any, Unit]
    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多