In Scala, you can use anonymous functions with map method. And here we will discuss the usage of multiple line anonymous functions with map. Therefore, whenever you see that your algorithm is becoming lengthy then instead of utilizing an anonymous function you can firstly define the method and then you can pass it into the map or use it with the map function.
Now, lets discuss some examples below.
Example: 1#
// Scala program of Using anonymous // functions with the map method // Creating object object GfG
{ // Main method
def main(args : Array[String])
{
// Defining anonymous function
def addTwo(a : Char) : Char = (a.toByte + 2 ).toChar
// Utilizing anonymous function
// with map method
val res = "Geeks" .map(addTwo)
// Displays output
println(res)
}
} |
Iggmu
In this example the method addTwo has a parameter of type Char as a string is a collection of Characters and when we call this addTwo method with the map function on the stated String then this map will work on one Char at a time.
Example: 2#
// Scala program of Using anonymous // functions with the map method // Creating object object GfG
{ // Main method
def main(args : Array[String])
{
// Creating a list of numbers
val list = List( 1 , 3 , 4 )
// Defining an anonymous function
// multiplyTwo
def multiplyTwo(i : Int) : Int = (i* 2 ).toInt
// Utilizing anonymous function
// with map method on a list of
// integers
val op = list.map(multiplyTwo)
// Displays output
println(op)
}
} |
List(2, 6, 8)
This is same as above example but here we have defined an anonymous function for multiplication and it multiplies all the integers of the list with the stated integer.