Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the responsive-lightbox domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114

Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the hueman domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114
Scala Anonymous Function - Testingpool

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...