Case classes as messages

In our "hello world" example, we constructed an actor that is expected to receive a string as message. Any object can be passed as a message, provided it is immutable. It is very common to use case classes to represent messages. This is better than using strings because of the additional type safety: the compiler will catch a typo in a case class but not in a string.

Let's rewrite our EchoActor to accept instances of case classes as messages. We will make it accept two different messages: EchoMessage(message) and EchoHello, which just echoes a default message. The examples for this section and the next are in the chap09/hello_akka_case_classes directory in the sample code provided with this book (https://github.com/pbugnion/s4ds).

A common Akka pattern is to define the messages that an actor can receive in the actor's companion object:

// EchoActor.scala

object EchoActor { 
  case object EchoHello
  case class EchoMessage(msg:String)
}

Let's change the actor definition to accept these messages:

class EchoActor extends Actor with ActorLogging {
  import EchoActor._ // import the message definitions
  def receive = {
    case EchoHello => log.info("hello")
    case EchoMessage(s) => log.info(s)  
  }
}

We can now send EchoHello and EchoMessage to our actors:

echo1 ! EchoActor.EchoHello
echo2 ! EchoActor.EchoMessage("We're learning Akka.")
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset