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#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
      
    }
}

chevron_right


Output:

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#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
      
    }
}

chevron_right


Output:

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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.