13.1. Getting Started with a Simple Actor
Problem
You want to begin using actors to build concurrency into your applications.
Solution
Create an actor by extending the akka.actor.Actor
class and writing a receive
method in your class. The receive
method should be implemented with a
case
statement that allows the actor
to respond to the different messages it receives.
To demonstrate this, create an SBT project directory named HelloAkka, move into that directory, and then add the necessary Akka resolver and dependency information to your build.sbt file:
name := "Hello Test #1" version := "1.0" scalaVersion := "2.10.0" resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/" libraryDependencies += "com.typesafe.akka" %% "akka-actor" % "2.1.2"
Note
At the time of this writing, the Akka actor library is being migrated into the Scala distribution, but it’s still necessary to include the library as a dependency in your SBT build.sbt file (or download the necessary JAR files manually). This may change in the future, in which case the dependencies shown in this chapter may not be necessary.
Next, define an actor that responds when it receives the String
literal hello
as a message. To do this, save the
following source code to a file named Hello.scala in the root directory of your SBT
project. Notice how the literal hello
is used in the first case
statement
in the receive
method of the HelloActor
class:
import
akka.actor.Actor
import
akka.actor.ActorSystem
import
akka.actor.Props ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.