Function literals

Let's have a look at an example:

class FunctionLiterals {
val sum = (a: Int, b: Int) => a + b
}

object FunctionLiterals {

def main(args: Array[String]): Unit = {
val obj = new FunctionLiterals
System.out.println(s"3 + 9 = ${obj.sum(3, 9)}")
}
}

Here, we can see how the sum field of the FunctionLiterals class is actually assigned a function. We can assign any function to a variable and then call it as if it was a function (essentially invoking its apply method). Functions can also be passed as parameters to other methods. Let's add the following to our FunctionLiterals class:

def runOperation(f: (Int, Int) => Int, a: Int, b: Int): Int = {
f(a, b)
}

We can then pass the required function to runOperation, as follows:

obj.runOperation(obj.sum, 10, 20)
obj.runOperation(Math.max, 10, 20)