Over a million developers have joined DZone.

Simplifying Monads in Scala

DZone 's Guide to

Simplifying Monads in Scala

Let's go over the importance of flatMaps to Monads in Scala to see what role the combinator plays and how to use them to simplify your Monad objects.

· Java Zone ·
Free Resource

Monads are not at all a complex topic, but yet it comes under the advanced section of Scala language. So basically, Monads are structures that represent sequential computations.

Let's be clear: A Monad is not a class or a trait; it is a concept.

A Monad is an object that wraps another object in Scala. In Monads, the output of a calculation at any step is the input to other calculations, which run as a parent to the current step.

One positive point: Assuming you already know about flatMaps in Scala and you know how to access future values using combinators (including flatMap), you already know the use case for flatMap. It flattens the resulting list of strings into a sequence of characters, as seen in the following example:

scala> var name = Seq("Nikhil", "Mateo")
name: Seq[String] = List(Nikhil, Mateo)

scala> var exMap = name.map(_.toLowerCase)
exMap: Seq[String] = List(nikhil, mateo)

scala> var exMap = name.flatMap(_.toLowerCase)
exMap: Seq[Char] = List(n, i, k, h, i, l, m, a, t, e, o)

Directly check the exact example of the Monad:

val numList1 = List(1,2)
val numList2 = List(3,4)

numList1 flatMap { x => numList2 map {
        y => x + y

Output: res10: List[Int] = List(4, 5, 5, 6)

Without a Monad:

for {
     | first <- numList1
     | second <- numList2
     | } yield first + second
res11: List[Int] = List(4, 5, 5, 6)

FlatMap is way more powerful than map. It gives us the ability to chain operations together, as you've seen in the previous section. Map's functionality is just a subset of flatMap's functionality.

If you want to have a map() available in your Monad, you can express it using a Monad's existing flatMap() and unit() methods like this:

(note that g is some function Int → Something, not Int → List[Something]):

m map g = flatMap(x => unit(g(x)))

Note: This is a quick post about Monads, and I will be writing more on them soon.

Though this isn't complete information, we're off to a good start. We have the practical idea behind monads. If you have suggestions please share, that would be a great for everyone to learn.

java ,scala ,monads ,flatmap ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}