Welcome, Akka Typed !!

Table of contents
Reading Time: 3 minutes

While I was attending ScalaDays Berlin 2018, I experienced many great ideas but the one which intrigued me the most was “Farewell Any => Unit, welcome Akka Typed!” by Heiko Seeberger where he explained about Akka Typed APIs. In this blog I am going to explain what I learned until now about Akka Typed, therefore, I named this blog “Welcome, Akka Typed !!”, so let’s start.

Before I start talking about Akka Typed APIs let’s first discuss what we have in Akka untyped and the problems. So in Akka untyped actor, we don’t know the type of message that we are passing. Why you may ask. Because if you look inside Akka API there is one abstract method receive() whose type is PartialFunction[Any, Unit] which is a partial function that takes any as input and return Unit.

So if I wanted to make an actor whose state starts with 0(zero) and adds every time we pass an integer with the previous state. In this case, an actor can be created as follows:

In the above example, there is a mutable variable, counter but the thing to be noted here is the pattern match that has been used. Here we want to add an integer to the counter but because of the Any => Unit, we can send anything we want. For example, if we pass a string we will get the timeout exception in case of Ask and we all know what will happen in the case of tell (fire and forget).

Now let’s look into the Akka Typed API usage as showcased in above snippet. This is similar to the previous but one thing is missing that is receive method which is replaced by onMessage. This is similar to the receive method which is invoked when it receives any message. If you look at the type of onMessage it returns Behavior of type T in our case it is TypedAdder.Command. Here in our example, we are not changing the behavior instead it returns the same behavior. Changing of behavior is very useful in maintaining states.

One thing here is we are using a mutable variable to maintain the state but according to Akka documentation immutable actor is recommended as the “default choice”. So now let’s look into how we can create similar kind of application without using a mutable variable.

Here we are using and leveraging the immutability feature of typed API. Also as you can observe from the above code that the behavior has been kept same when the actor receives PrintCounter message using Behaviours.same but on receiving the Add message we are changing the Behaviour by calling TypedAdder apply() method with updated state and another thing is to be noted is that actor has not been enclosed in class and that’s how the actor is created in immutable style in new Akka Typed API.

Here I conclude this blog. I have given a brief introduction about how to create a basic actor using Akka Typed APIs. In my further blogs, I will discuss Akka Typed with more details.


Written by 

I am from India and developing Scala Microservices :)