Created
September 2, 2014 09:11
-
-
Save 2m/1695454e19fff3260dc8 to your computer and use it in GitHub Desktop.
Stackable trait with context.become
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package stackable | |
import akka.actor.{Props, ActorSystem, Actor} | |
object Main extends App { | |
val sys = ActorSystem("stackable") | |
val act = sys.actorOf(Props[EchoActor]) | |
act ! "BooHoo" | |
act ! "BooHoo" | |
act ! "BooHoo" | |
System.in.read() | |
sys.shutdown() | |
sys.awaitTermination() | |
} | |
trait Behaviour { self: Actor => | |
var wrapped: Receive = _ | |
def receive: Receive = { | |
case msg => if (wrapped.isDefinedAt(msg)) wrapped(msg) else unhandled(msg) | |
} | |
} | |
trait FunnyTracer extends Behaviour { self: Actor => | |
override def receive = { | |
case msg => | |
println("Mooo!") | |
super.receive(msg) | |
println("Oink oink!") | |
} | |
} | |
class EchoActor extends Actor with FunnyTracer { | |
def statefulReceive: Int => Receive = (i: Int) => { | |
case msg => | |
println(s"Received $msg while storing $i") | |
wrappedBecome(statefulReceive(i+1)) | |
} | |
def wrappedBecome(r: Receive) = { | |
wrapped = r | |
} | |
wrappedBecome(statefulReceive(0)) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> sbt run | |
Mooo! | |
Received BooHoo while storing 0 | |
Oink oink! | |
Mooo! | |
Received BooHoo while storing 1 | |
Oink oink! | |
Mooo! | |
Received BooHoo while storing 2 | |
Oink oink! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment