0
votes

From the Akka documentation:

Actors are implemented by extending the Actor base trait and implementing the receive method. The receive method should define a series of case statements (which has the type PartialFunction[Any, Unit]) that defines which messages your Actor can handle, using standard Scala pattern matching, along with the implementation of how the messages should be processed.

Code:

class MyActor extends Actor {
  val log = Logging(context.system, this)

  def receive = {
    case "test" ⇒ log.info("received test")
    case _      ⇒ log.info("received unknown message")
  }
}

There is no input to receive, so what is being matched in the case statements? Also, how does PartialFunction[Any, Unit] come into the picture here?

2

2 Answers

2
votes

Actors are message-driven and input is fed to an actor like messages sent to a mailbox. Messages are most commonly sent to an actor via the fire-and-forget tell (i.e. !), like:

myActor ! "test"

The receive method in an actor allows one to pattern-match the messages (generally by type) to process them accordingly. The method has type PartialFunction[Any, Unit] so that:

  1. case pattern-matching, which is a partial function, fits well as a screening tool to effectively handle various types of incoming messages

  2. it can take messages of any type, process them in any way necessary and doesn't need to return anything, like:

    case i: Int => // do something with i
    case s: String => // do something with s
    // ...
    

Note that in the case of unhandled messages, under the hood an UnhandledMessage() will be published to the ActorSystem.

0
votes

The message passed to the actor is matched eg: if actor ! "message" is called, then "message" is matched.

see here

https://alvinalexander.com/scala/how-to-communicate-send-messages-scala-akka-actors

PartialFunction[Any, Unit] comes into picture because because it accepts argument of Any type but doesn't return anything. If "message" is passed to the actor then String is the type of parameter that is passed to PartialFunction. During pattern match, it doesn't return a value. So Unit return type.