Saturday, 18 December 2021

Monads in Scala

Monads belongs to Advance Scala concepts. It is not a class or a trait; it is a concept. It is an object which covers other object.

A Monad represents an object that wraps another object in Scala. Each step in Monads has an output that serves as input for subsequent steps. Although, Scala's maximum collections are Monads, but not all Monads are collections. Some Monads, for example, can be used as containers like Options.

In a brief, the data types that implement map() and flatMap() (such as Options, list) in Scala are called Monads.

There are 2 operations provided by Monads -

1. unit(): It doesn't return any value

2. flatMap(): It returns a series in place of returning a single component.


Example: Seq is a Monad as we can apply map() and flatMap() on it.

val temp = Seq("Krishna", "Kumar", "Chourasiya")

    val temp1 = temp.map(_.toUpperCase)

    //output => List(KRISHNA, KUMAR, CHOURASIYA) 

    val temp2 = temp.flatMap(_.toUppercase)

    //output => List(K, R, I, S, H, N, A, K, U, M, A, R, C, H, O, U, R, A, S, I, Y, A)




Monads in Scala

Monads belongs to Advance Scala   concepts. It  is not a class or a trait; it is a concept. It is an object which covers other object. A Mon...