Skip to content

Instantly share code, notes, and snippets.

@prassee
Last active December 11, 2016 02:12
Show Gist options
  • Save prassee/8a4bc61b37c15c6cc90ce94e9373ad86 to your computer and use it in GitHub Desktop.
Save prassee/8a4bc61b37c15c6cc90ce94e9373ad86 to your computer and use it in GitHub Desktop.
HyScala Dec 2016 - Introduction to Akka : code examples
repo
====
https://github.com/prassee/hyscala-akka-intro-talk
build.sbt
=========
name := "hyscala-akka-intro-talk"
version := "1.0"
scalaVersion := "2.11.8"
libraryDependencies ++= Seq("com.typesafe.akka" %% "akka-actor" % "2.4.14")
Code
====
package hyscala.akka.intro
import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import scala.collection.mutable.ListBuffer
/**
* plain bare minimum actor
*/
class PlainActor extends Actor {
println("")
def receive: Receive = {
case _ =>
}
}
class PrimitiveHandlingActor extends Actor {
def receive: Receive = {
case "hello world" => println("""received hello world """)
case 11 => println("received ")
case _ => println("some other data type")
}
}
// case class
case class Item(name: String, quantity: Int, rate: Double)
case object Done
case class Order(items: List[Item])
case class Bill(double: Double)
class CartActor(billingActor: ActorRef, cartName: String) extends Actor {
private val items = ListBuffer[Item]()
def receive: Receive = {
case item: Item => items.+=(item)
case Done =>
billingActor ! Order(items.toList)
items.clear()
}
}
class BillingActor extends Actor {
def receive: Receive = {
case order: Order => println(s"""Heres your bill
|${Bill(order.items.foldLeft(0.0)((a, b) => a + (b.quantity * b.rate)))}""".stripMargin)
}
}
object AkkaIntroTalk extends App {
val actorSystem = ActorSystem("actorsystem")
val billingActor: ActorRef = actorSystem.actorOf(Props[BillingActor], "billingActor")
val cartActor: ActorRef = actorSystem.actorOf(Props(classOf[CartActor], billingActor, "cart1"), "cartActor")
cartActor ! Item("Apple", 3, 20.0)
cartActor ! Item("Orange", 3, 15.0)
cartActor ! Item("Butter", 1, 70.0)
cartActor ! Done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment