Over a million developers have joined DZone.

Typed ask for Akka

DZone's Guide to

Typed ask for Akka

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

Akka is a great tool for writing distributed applications. One thing that always surprised me though is that while being based on Scala, which is a very type-safe language, the elementary construct in Akka – an actor – is not really type safe. You can send any message to any actor, and get back any object in reply.

The upcoming 2.2 release of Akka will contain an experimental implementation of typed channels, which use macros to ensure type-safety in actor communication; but before that is final, here’s a simpler and less powerful approach, to add some typing to the ask pattern.

You can look at the ask pattern as a kind of asynchronous method invocation: you send a message (its class corresponds to the method name) with some arguments, and expect a reply (method result). More specifically, we get back a Future, which will eventually hold the reply (if any). Note that the reply can also be of type Unit, corresponding to methods returning no result. Knowing when such “methods” complete may still be useful, though.

A very simple example of the basic ask pattern usage:

import akka.pattern.ask
case class LookupUser(id: Int)
// the actor impl should send back a message to the sender
val userFuture = actor ? LookupUser(10)
// userFuture: Future[Any]
userFuture onSuccess {
   case result => {
      // do something with the result
      // result has type Any 

The not-so-nice thing here is that the return type of ? (see the AskSupport implementation) isFuture[Any], as the actor may respond with any message. However ideally, when sendingLookupUser we would want to get a Future[Option[User]], when sending UserCount aFuture[Int] and so on.

This is in fact quite easy to implement. First of all, we must somehow embed the expected reply type in the message. For that we can use a trait, which takes the type of the expected response as a type parameter:

trait Replyable[T]

This can be used in the messages that we are sending to the actor:

case class LookupUser(id: Int) extends Replyable[Option[User]]
case class UserCount() extends Replyable[Int]

Now we need a variant of ? which returns a future with the right type parameter:

trait ReplySupport {
  implicit class ReplyActorRef(actorRef: ActorRef) {
    def ?[T](message: Replyable[T])
            (implicit timeout: Timeout, tag: ClassTag[T]): Future[T] = {
      akka.pattern.ask(actorRef, message).mapTo[T]
package object reply extends ReplySupport

You can see that we are simply re-using the existing ask implementation, and mapping the resulting future to the right type. The timeout is an implicit parameter of ask and ClassTag of mapTo, hence we must include them in the signature as well.

Usage is quite simple, in fact it’s almost the same as before, except for the import and that the future is of the right type:

import reply._
val userFuture = actor ? LookupUser(10)
// userFuture: Future[Option[User]]
userFuture onSuccess {
   case result => {
      // do something with the result
      // result has type Option[User] 

That’s the actor-user side. What about the actor itself? How to ensure that if an actor receives a message of type Replyable[T], it will actually answer with T? As quite commonly in Scala, the answer again is a trait, which can be mixed into an actor:

trait ReplyingActor extends Actor {
  def receive = {
    case m: Replyable[_] if receiveReplyable.isDefinedAt(m) => {
      try {
        sender ! receiveReplyable(m)
      } catch {
        case e: Exception => sender ! Failure(e)
  def receiveReplyable[T]: PartialFunction[Replyable[T], T]

And example usage:

class UserActor extends ReplyingActor {
   def receiveReplyable[T] = {
      case LookupUser(id) => Some(User(...))
      case UserCount() => 512

Now this is all nicely type-checked. If we tried to return a String in the UserCount branch, we would get a compile-time error.

Hope this will be helpful – and comments as always are welcome!


Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}