17
votes

How can I use Akka Actor ask and maintain type safety? or avoid using ask in favour of tells?

When calling ? or ask on an Akka Actor, a Future[Any] is returned and I have to do an explicit cast via future.mapTo[MyType].

I don't like losing this type safety. If I use Futures directly (with no actors) I can explicitly return Future[MyType] and maintain type safety.

My specific use case involves an actor delegating it's message to two child actors and then aggregating the results from those actors and returning that to the parent's sender. My parent's receive method looks similar to this approach in the Akka Docs:

http://doc.akka.io/docs/akka/2.0/scala/futures.html#For_Comprehensions

val f1 = actor1 ? msg
val f2 = actor2 ? msg

val f3 = for {
  a ← f1.mapTo[Int]
  b ← f2.mapTo[Int]
  c ← ask(actor3, (a + b)).mapTo[Int]
} yield c

Is there a better way to achieve my use case?

2
Thanks. I must have missed that bit in the docs - they seems to fit the bill. The section 'When to use Typed Actors' and the linked blog post were both a good read and make a good case for why Actors are untyped. I'm now thinking I will try to stick with untyped actors. If you post as an answer I will accept it.theon

2 Answers

8
votes

Try typed actors. Basically they allow you to interact with an actor using strongly typed traits/interfaces rather than by exchanging messages. Behind the scenes Akka implements these interfaces with a dynamic proxy and does the asynchronous magic.

Typed actor can return have methods with different, strongly typed return values (from documentation mentioned above):

def squareDontCare(i: Int): Unit //fire-forget

def square(i: Int): Future[Int] //non-blocking send-request-reply

def squareNowPlease(i: Int): Option[Int] //blocking send-request-reply

def squareNow(i: Int): Int //blocking send-request-reply

These method represents tell while the remaining ones are different flavours of ask.

9
votes

I wanted to post a new answer because @Roland Kuhn recently presented a new solution for this called Typed Channels:

val f: Future[MyType] = actor <-?- message