Scala Anonymous Function

In scala, when a function is written without a name is know as anonymous function, also called function literal – so you can pass it into a method that takes a function as an argument or assign it to a variable. Let’s understand it with an example below.

Suppose we have a list as given below and we want to pass an anonymous function to filter method of that list, so it can provide us a new list containing only even number.

object evenNumber {

  def main(args: Array[String]): Unit = {
    val x = List.range(1,10)
    val newList = x.filter((i:Int)=> i % 2 == 0)   //Passing anonymous function in filter method
    print(newList)
  }
}
Output: List(2, 4, 6, 8)

In the above example, anonymous function is “(i:Int)=> i % 2 == 0” , that does not have any name and passed as an argument in filter method.

Let’s see one more example where we are creating an anonymous function which concatenate first name and last name.

object printname {
  def main(args: Array[String]): Unit = {
    var name = (FirstName:String,LastName:String)=>FirstName+" "+LastName
    print(name("Bill","Gates"))
  }
}
Output: Bill Gates
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...