I have this akka actor:
class Counter2 extends Actor {
def counter(n:Int):Receive = {
case "incr" => context.become(counter(n+1))
case "get" => sender ! n
}
def receive = counter(0)
}
The counter
function performs pattern matching against the value that is received by the receive
function.
How can the counter()
"know" that the pattern matching has to be done with the values received by receive
?
The return value of the method receive
is of type Receive
which is an alias for PartialFunction[Any, Unit]
. Thus, the incoming actor messages are not given to receive
but Akka calls receive
to obtain the messaging function. This function is then applied to the incoming messages. In your case the partial function is defined by counter(n: Int)
, a function which is instantiated with a specific value for n
.