Everything you need to know about Monad in Scala

Reading Time: 2 minutes

Introduction of Monad in Scala

Monad in scala are a category of data types. Informally, anything that has a type parameter, a constructor that takes an element of that type, and a flatMap method (which has to obey certain laws) is a monad.

A monad is a mechanism for sequencing computations.

Firstly, Monad is a construction which performs successive calculations. Secondly, it is an object which covers the other object. It is worth noting that here, the output of an operation at some step is an input to another computations, which is a parent to the recent step of the program declare.

Laws of Monad in Scala

If the monad satisfies the three laws, then we guarantee that any sequence of applications of the unit and the flatMap functions leads to a valid monad. In other words, the monad’s effect to a value still holds.

Monads and their laws define a design pattern from a programming perspective, a truly reusable code resolving a generic problem.

The three monad laws are:

  • Left identity
  • Right identity
  • Associativity

Left identity

Left identity, says that applying a function f using the flatMap function to a value x lifted by the unit function is equivalent to applying the function f directly to the value x:

Monad.unit(x).flatMap(f) = f(x)

Right identity

It states that application of the flatMap function using the unit function as the function f results in the original monadic value:

x.flatMap(y => Monad.unit(y)) = x


This law says that applying two functions and g to a monad value using a sequence of flatMap calls is equivalent to applying g to the result of the application of the flatMap function using as the parameter.

x.flatMap(f).flatMap(g) = o.flatMap(x => f(x).flapMap(g))