Home »
Scala
Monads in Scala
By IncludeHelp Last updated : October 26, 2024
Scala Monads
Monad is a tricky concept of the Scala programming language. It is a wrapper of the object type, an object that wraps another object. It is not a trait nor class. Also, most of the collections are monads but the reverse is not possible.
A monad is a data type that implements map and flatMap() like lists, options, etc.
Operations of Monads
- unit(): The
unit
wraps a value in a monad without returning any data type.
- flatMap(): The
flatMap()
is similar to the map()
and it returns a series of data types instead of a single value.
- map(): The
map()
applies on a function that returns a plain value and wraps the result back in the original monad.
- filter(): It filters values within the monad based on a predicate function.
- for-comprehensions: This is a way to chain
map
, flatMap
, and filter
, enhancing code readability.
Example of Monads
Let's take an example to understand the working of methods of monads.
object MyObject {
def main(args: Array[String]): Unit = {
val setA = Set(4, 6, 8, 2)
val setB = Set(3, 5, 7, 1)
// Using flatMap and map to multiply each element
// of setA with each element of setB
val multiple = setA.flatMap { a =>
setB.map { b =>
a * b
}
}
// Using for-comprehensions to achieve
// the same result
val forCompMultiple = for {
a <- setA
b <- setB
} yield a * b
println("Multiplication of SetA and SetB using flatMap and map is:\n" + multiple)
println("Multiplication of SetA and SetB using for-comprehensions is:\n" + forCompMultiple)
}
}
Output
Multiplication of SetA and SetB using flatMap and map is:
HashSet(14, 20, 6, 28, 2, 12, 18, 40, 8, 30, 4, 10, 56, 42, 24)
Multiplication of SetA and SetB using for-comprehensions is:
HashSet(14, 20, 6, 28, 2, 12, 18, 40, 8, 30, 4, 10, 56, 42, 24)
Explanation
In the above program, to have used the flatMap() method to find the multiplication of elements of two sets. It has mapped (multiplied) each element of setA to all elements of setB. And the resultant is a set containing all possible maps.