我想知道为什么这段代码中的akka Actor的receive方法表现得像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。
关于这种行为的任何想法,为什么这里的def计算像val?
答案 0 :(得分:4)
receive
返回PartialFunction [Any,Unit],并且PartialFunction被播种为Actors行为(可以使用context.become / unbecome更改)。
将其视为val
的原因是PartialFunction实例在更改之前重复使用。