- Open the project Hello-Akka in an IDE like intelliJ Idea, and create a Scala file, BehaviorAndState.scala, inside the package, com.packt.chapter1.
- Add an import to the top of the file: import akka.actor.Actor.
Inside the file, define the actor as follows:
class SummingActor extends Actor {
// state inside the actor
var sum = 0
// behaviour which is applied on the state
override def receive: Receive = {
// receives message an integer
case x: Int => sum = sum + x
println(s"my state as sum is $sum")
// receives default message
case _ => println("I don't know what
are you talking about")
}
}
Here, we are not creating an actor, we are only defining the state and behavior.
- From the previous recipe, we know that ActorSystem is the home for actors, and we know how to create an ActorSystem. Now, we will create the actor inside it.
Add the following imports to the top of the file:
import akka.actor.Props
import akka.actor.ActorSystem
object BehaviourAndState extends App {
val actorSystem = ActorSystem("HelloAkka")
// creating an actor inside the actor system
val actor = actorSystem.actorOf(Props[SummingActor])
// print actor path
println(actor.path)
}
- Run the preceding application from the IDE or from the console, and it will print the actor path.
You can run the application from the console using the following command:
sbt "runMain com.packt.chapter1.BehaviorAndState"
akka://HelloAkka/user/$a
Here, HelloAkka is the ActorSystem name, user is the user guardian actor, that is, the parent actor for your actor, and $a is the name of your actor.
You can also give a name to your actor:
val actor = actorSystem.actorOf(Props[SummingActor],
"summingactor")
If you run the application again, it will print the actor name as summingactor.
The output will be as follows:
akka://HelloAkka/user/summingactor
How do we create an actor if it takes an argument in the constructor as shown in the following code:
class SummingActorWithConstructor(intitalSum: Int)
extends Actor {
// state inside the actor
var sum = 0
// behaviour which is applied on the state
override def receive: Receive = {
// receives message an integer
case x: Int => sum = intitalSum + sum + x
println(s"my state as sum is $sum")
// receives default message
case _ => println("I don't know what
are you talking about")
}
}
For this, we use the following code:
actorSystem.actorOf(Props(classOf[
SummingActorWithConstructor], 10), "summingactor")