Skip to content

Instantly share code, notes, and snippets.

@mergeconflict
Last active December 19, 2015 06:29
Show Gist options
  • Save mergeconflict/5912218 to your computer and use it in GitHub Desktop.
Save mergeconflict/5912218 to your computer and use it in GitHub Desktop.
Akka continuation-passing style?
package sandbox
import akka.actor.{ Actor, ActorRef, ActorSystem, Props }
class Println extends Actor {
def receive = {
case message => println(message)
}
}
object Println {
val props = Props[Println]
}
class Add extends Actor {
def receive = {
case (a: Int, b: Int) => sender ! a + b
}
}
object Add {
val props = Props[Add]
}
class Square extends Actor {
def receive = {
case (a: Int) => sender ! a * a
}
}
object Square {
val props = Props[Square]
}
class Pythagoras(add: ActorRef, square: ActorRef) extends Actor {
import Pythagoras._
def receive = {
case (a: Int, b: Int) =>
val k = context.actorOf(Join.props(add, sender))
square.tell(a, k)
square.tell(b, k)
}
}
object Pythagoras {
def props(add: ActorRef, square: ActorRef) = Props(classOf[Pythagoras], add, square)
private class Join(add: ActorRef, k: ActorRef) extends Actor {
def receive = {
case aSquared: Int => context become {
case bSquared: Int => try {
add.tell((aSquared, bSquared), k)
} finally context.stop(self)
}
}
}
object Join {
def props(add: ActorRef, k: ActorRef) = Props(classOf[Join], add, k)
}
}
object Main extends App {
implicit val system = ActorSystem("cps")
val println = system.actorOf(Println.props, "println")
val add = system.actorOf(Add.props, "add")
val square = system.actorOf(Square.props, "square")
val pythagoras = system.actorOf(Pythagoras.props(add, square), "pythagoras")
pythagoras.tell((3, 4), println)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment