akka Hello world Akka hello world (Scala)


Example

  1. Add akka-actor dependency (SBT example)
libraryDependencies += "com.typesafe.akka" % "akka-actor_2.11" % "2.4.8"
  1. Create actor classes:

Actor for string output:

class OutputActor extends Actor {
  override def receive: Receive = {
    case message => println(message)
  }
}

Actor for string modifying:

class AppendActor(outputActor: ActorRef) extends Actor {
  override def receive: Receive = {
    case message: String =>
      val changed = s"Hello, $message!"
      outputActor ! changed

    case unknown =>
      println(s"unknown message: $unknown")
  }
}
  1. Create actor systems and send message
object HelloWorld extends App {
  val system = ActorSystem("HelloWorld")
  val outputActor = system.actorOf(Props[OutputActor], name = "output")
  val appendActor = system.actorOf(Props(classOf[AppendActor], outputActor), name = "appender")

  appendActor ! "Akka" // send test message
  Thread.sleep(500) // wait for async evaluation
  system.terminate() // terminate actors system
}

Program output:

Hello, Akka!