Monad Transformer Example

Sarath Kallatt Sivasankaran
1 min readMar 24, 2019

--

OptionT — Practical use case for a Monad Transformer

On an opportunity journey, the interviewer put a problem in front of me. I am putting a better example here for simplicity.

There is a function getDepartment which gives you a Future[Option[Department]] given a department id and another function which gives you Future[Option[Employee]] given a employee id. Now you are asked to implement getDepartmentWithEmployees using these two functions.

At first it looks so simple and if you are a beginner in Scala, you start with a for comprehension to solve the problem as follows

The implementation looks a little dirty and hackish, that’s mainly because you have to do different conversions yourself for example from List[Future[Option[Employee]]] to Future[List[Option[Employee]]] and List[Option[Employee]] to List[Employee].

Question that arises is can we do better and make it more simple? That’s how I learned OptionT (Monad Transformer) from cats library. Here is a sample solution with OptionT monad transformer

This looks better. You still need to do sequence two times one to convert List[Future[Option[Employee]]] to Future[List[Option[Employee]]] and then to convert List[Option[Employee]] to Option[List[Employee]]. But with cats library, it is very easy. You just need to do import cats.implicits._ and you can call sequence on all well known monads.

You can read more on OptionT from cats OptionT documentation. And here is another good explanation from a medium article

--

--

No responses yet