Reputation: 259
I am wondering why the receive method of akka Actor in this code behaves like a 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()
}
The output:
in receive
Hello Akka
Hello Akka
Hello Akka
when it is supposed to be:
in receive
Hello Akka
in receive
Hello Akka
in receive
Hello Akka
while the receive is a def.
Any idea about this behavior, why the def here compute like a val ??
Upvotes: 3
Views: 252
Reputation: 26579
receive
returns a PartialFunction[Any, Unit], and that PartialFunction is seeded as the Actors behavior (can be changed with context.become/unbecome).
The reason for it to be perceived as a val
is that the PartialFunction instance is reused until changed.
Upvotes: 4