Scala Anonymous Functions

Scala  supports a facility to avoid naming functions. This provides convenience when working with higher order functions where the need is to pass a function as a parameter to another function. These are referred to as anonymous functions or function literals

A simple anonymous function.

(x : Int) => x * x 

Here x : Int is the parameter and right side is the body of the function.

An example of anonymous function with multiple parameters.

( x: Int, y : Int) => x + y

Another example of anonymous function with no parameters.

() => { Calendar.getInstance().getTime() }

Anonymous functions can be saved into vals.

scala> val add = (x : Int, y : Int ) => x + yadd: (Int, Int) => Int = <function2>scala> add(10, 20)res1: Int = 30

Benefits of anonymous functions can be observed when working with higher order functions. In this example we have a higher order function which returns a function as a result. The higher order function giveMe takes a String as input and returns a function (anonymous function) which takes two Int’s as input and returns an Int.

object HigherOrderFunctionTest1 {// Higher order functiondef giveMe(t : String) : (Int, Int) => Int  = t match {case "sum" => (x, y) => x + ycase "sub" => (x, y) => x - ycase "mult" => (x, y) => x * ycase "div" => (x, y) => x / y}def main(args: Array[String]) {println(giveMe("sum")(20, 10))println(giveMe("sub")(20, 10))println(giveMe("mult")(20, 10))println(giveMe("div")(20, 10))}}

Proceed to read other Scala Tutorials.