Let's define an actor that computes something, say, the Fibonacci of a number:
- Create a Scala file, FibonacciActor.scala, in the package com.packt.chapter1.
- Add import to the top of the file:
import akka.actor.Actor
Now we define an actor which computes the Fibonacci of a number:
class FibonacciActor extends Actor {
override def receive: Receive = {
case num : Int =>
val fibonacciNumber = fib(num)
}
def fib( n : Int) : Int = n match {
case 0 | 1 => n
case _ => fib( n-1 ) + fib( n-2 )
}
}
- As of now, we have defined the actor. To send the computed result back to the sender, we have to add one more line to the actor code:
sender ! fibonacciNumber
Now, notice the difference:
class FibonacciActor extends Actor {
override def receive: Receive = {
case num : Int =>
val fibonacciNumber = fib(num)
sender ! fibonacciNumber
}
def fib( n : Int) : Int = n match {
case 0 | 1 => n
case _ => fib( n-1 ) + fib( n-2 )
}
}
Actors, by their implementation, know the default immediate sender, that is, they know who has sent them the message.
- Create an application which asks for result from the actor.
- Add the following imports to the top of file:
import akka.actor.{Props, ActorSystem}
import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.Await
import scala.concurrent.duration._
- Create an object, FibonacciActorApp as follows:
object FibonacciActorApp extends App {
implicit val timeout = Timeout(10 seconds)
val actorSystem = ActorSystem("HelloAkka")
val actor = actorSystem.actorOf(Props[FibonacciActor])
// asking for result from actor
val future = (actor ? 10).mapTo[Int]
val fiboacciNumber = Await.result(future, 10 seconds)
println(fiboacciNumber)
}
- Run the preceding application in the IDE-like intelliJ Idea or from the console, and you will get the following output: