Using anonymous functions with the map method in Scala
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#
object GfG
{
def main(args : Array[String])
{
def addTwo(a : Char) : Char = (a.toByte + 2 ).toChar
val res = "Geeks" .map(addTwo)
println(res)
}
}
|
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#
object GfG
{
def main(args : Array[String])
{
val list = List( 1 , 3 , 4 )
def multiplyTwo(i : Int) : Int = (i* 2 ).toInt
val op = list.map(multiplyTwo)
println(op)
}
}
|
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.
Last Updated :
06 Mar, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...