Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Receive Actor method in akka behaves like a val?

Tags:

scala

akka

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 ??

like image 694
SaKou Avatar asked Dec 06 '25 07:12

SaKou


1 Answers

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.

like image 151
Viktor Klang Avatar answered Dec 07 '25 22:12

Viktor Klang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!