Explore Id Monad in Cats

Reading Time: 3 minutes

Today we are going to explore Id Monad in Cats. If you don’t know about Monad I’ll suggest you go through this blog and then read this for better understanding.

What is Id Monad?

According to the referenced book:

Id is actually a type alias that turns an atomic type into a single-parameter type constructor.

Ahan! So, did you understand something?

Let me explain it to you.

Id Monad just provides you a monadic instance for the non-monadic types.

Let’s understand it with an example

The type of “int” should be Int but here I have explicitly mentioned its type as Id[Int]. Even after that, it shows no compilation error. This is because the Id monad wraps the Int(a non-monadic type) into Id(a monadic type). This way we can have a monadic representation for any non-monadic value.

The Need of Id Monad

Id Monad allows us to abstract over monadic and non-monadic code i.e we can use monadic types as well as non-monadic types in the code without any issue.

Let’s understand it with an example:

The above methods accept two Monads and return a Monad after concatenation of the String.

But what if I want to concatenate simple String?

Should I write a different function for that? I can, but it will be much of code duplicacy and we should avoid it. So for this purpose, we can use Id Monad.

Id has made it so easy. It can be considered as a wrapper over non-monadic types which wrap them in monadic type and make them work as a monad.

The Usefulness of Id Monad

One of the most prominent use of Id Monad is in testing of asynchronous code synchronously. We can write asynchronous code wrapped in Future but while testing the same we can avoid asynchronous call.

This can be done as follows:

Now we can use RealUptimeClient for main code and TestUptimeClient in testing.

That’s all for this blog. I hope it was helpful 😀

Share your feedback in the comment section below.

Reference

Written by 

Muskan Gupta is a Software Consultant having almost 1-year experience. She has knowledge of languages like C, C++, Java and Scala. She is familiar with Object-Oriented Programming Paradigms and also has an interest in relational database technologies. Her hobbies include travelling, reading novels and listening to music.

1 thought on “Explore Id Monad in Cats4 min read

Comments are closed.