Created
January 31, 2014 11:48
-
-
Save Mortimerp9/8730637 to your computer and use it in GitHub Desktop.
TypedActorRef for akka using unboxed tagged types. This does not type the messages, it only allows you to require a particular type of actor when taking `ActorRef` as parameter. This is useful when you are passing actors reference around and you are sure of the implementation type of this actor. It makes reading complex Akka code a bit easier, b…
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
| //Hello world from https://github.com/typesafehub/activator-hello-akka | |
| import TypedActorRef._ | |
| import akka.actor.{ActorRef, ActorSystem, Props, Actor} | |
| import akka.pattern.ask | |
| import akka.util.Timeout | |
| import scala.concurrent.duration._ | |
| val system = ActorSystem("helloakka") | |
| val greeter: ActorRef = system.actorOf(Props[Greeter], "greeter") | |
| val typedgreeter: TypedActorRef[Greeter] = greeter.typed[Greeter] | |
| def doSomething(gr: TypedActorRef[Greeter]) { gr ! WhoToGreet("akka") } | |
| /* Will not compile: | |
| doSomething(greeter) | |
| <console>:21: error: type mismatch; | |
| found : greeter.type (with underlying type akka.actor.ActorRef) | |
| required: com.qf.feed.util.akka.TypedActorRef.TypedActorRef[Greeter] | |
| (which expands to) akka.actor.ActorRef with AnyRef{type Tag = Greeter} | |
| doSomething(greeter) | |
| ^ | |
| */ | |
| doSomething(typedgreeter) | |
| implicit val timeout = new Timeout(5 seconds) | |
| val f = typedgreeter ? Greet | |
| val msg = scala.concurrent.Await.result(f, 10 seconds) | |
| println(msg) |
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
| //inspired by https://groups.google.com/forum/#!msg/akka-user/THMgHyO21To/SVpzfxw-1NQJ | |
| object TypedActorRef { | |
| type TypedActorRef[T <: Actor] = ActorRef @@ T | |
| implicit class ActorRefTyper(ref: ActorRef) { | |
| def typed[T <: Actor] = ref.asInstanceOf[TypedActorRef[T]] | |
| } | |
| } |
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
| //from https://coderwall.com/p/l-plmq | |
| type Tagged[U] = { type Tag = U } | |
| type @@[T, U] = T with Tagged[U] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment