Home » Scala language

Monads in Scala

Scala | Monads: In this tutorial on Scala monads, we will learn about the monads with working code and examples.
Submitted by Shivang Yadav, on March 06, 2020

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(): does not return any data type.
  • flatMap(): a map() like the method that returns a series of data types instead of a single component.

Let's take an example to understand the working of methods of monads.

object myObject 
{ 
	def main(args:Array[String]) 
	{ 
		val setA = Set(4, 6, 8, 2) 
		val setB = Set(3, 5, 7, 1) 
		val multiple = setA flatMap { q => setB map { r=>q*r } } 
		
		print("Multiplication of SetA and SetB is : ")
		println(multiple)
	} 
} 

Output

Multiplication of SetA and SetB 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.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.