Partial Functions and Modularizing Actor Receive blocks

Table of contents
Reading Time: 2 minutes

A partial function is defined as

It is a unary function which defines a domain. Not all values of A would be a part of the domain. For instance, in the following code block

The odd values of A would not match the domain. We can check this by the abstract method isDefined which is available for partial functions.

abstract def isDefinedAt(x: A): Boolean

Hence the above defined partial function would match for even values and not for the odd values. Something like the following calls would result in the expected output

Interestingly, PartialFunction offers a method called orElse which allows us to combine domains.

Hence, in the above scenario, if we have an alternate isOdd PartialFunction defined like this

Then we can combine the 2 domains together with an orElse to get something like this

Ok, so far so good. Now how do we take it to the actors. Simple, the Actor.Receive is a PartialFunction.

So let us assume that we want to modularize code now on the basis of infrastructure events and our application events.

So say we define one receive block like this

and another one like this

and now we combine the 2 domains so that our actor is able to deal with both kinds of incoming events

This way, we would be able to keep our receive blocks modularized and still be able to handle all the messages by combining the domains together.

Written by 

Vikas is the CEO and Co-Founder of Knoldus Inc. Knoldus does niche Reactive and Big Data product development on Scala, Spark, and Functional Java. Knoldus has a strong focus on software craftsmanship which ensures high-quality software development. It partners with the best in the industry like Lightbend (Scala Ecosystem), Databricks (Spark Ecosystem), Confluent (Kafka) and Datastax (Cassandra). Vikas has been working in the cutting edge tech industry for 20+ years. He was an ardent fan of Java with multiple high load enterprise systems to boast of till he met Scala. His current passions include utilizing the power of Scala, Akka and Play to make Reactive and Big Data systems for niche startups and enterprises who would like to change the way software is developed. To know more, send a mail to hello@knoldus.com or visit www.knoldus.com

1 thought on “Partial Functions and Modularizing Actor Receive blocks2 min read

  1. Scala 2.11 gives an error on that last line of code in your (very nice) article: a type was inferred to be `Any`; this may indicate a programming error

Comments are closed.