Skip to content

Instantly share code, notes, and snippets.

@nraychaudhuri
Last active August 29, 2015 14:05
Show Gist options
  • Save nraychaudhuri/c24204a632eba25e336b to your computer and use it in GitHub Desktop.
Save nraychaudhuri/c24204a632eba25e336b to your computer and use it in GitHub Desktop.
Typed Akka actor ref
//PLEASE NOTE: Typing actor refs are really hard problem(take a look at the discussions in Akka mailing list regarding this subject). This is no way a complete solution. This will only work if you know all the possible
//messages an actor can handle (that means no become/unbecome business).
package experiment
import akka.actor.{Props, ActorSystem, Actor, ActorRef}
case class TypedActorRef[A](actorRef: ActorRef) extends AnyVal {
def ![B](msg: B)(implicit ev: A <:< B, sender: ActorRef = Actor.noSender) = actorRef ! msg
}
object Provider {
type MessageTypes = IntMessage with StringMessage
case class IntMessage(i: Int)
case class StringMessage(s: String)
}
class Provider extends Actor {
import Provider._
override def receive = {
case IntMessage(i) =>
println("Got int")
case StringMessage(s) =>
println("Got string")
case s =>
println("No one should be allowed to send random message like this one " + s)
}
}
object Experiment extends App {
val sys = ActorSystem("test")
val ref = sys.actorOf(Props[Provider])
val typedRef = TypedActorRef[Provider.MessageTypes](ref)
typedRef ! Provider.IntMessage(20)
typedRef ! Provider.StringMessage("hey")
//this wil not compile
typedRef ! "will not work"
scala.io.StdIn.readLine()
sys.shutdown()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment