Scala Reactive Programming
上QQ阅读APP看书,第一时间看更新

Scala anonymous functions

In previous sections, we defined a couple of Scala functions and came to know that each function has a meaningful name. Is it possible to define a function without a name? Yes, in Scala, we can define a function without a name.

An anonymous function is a function without a name. It is also known as a function literal. It works just like a normal function. Let's explore it with some examples now:

def add (a: Int, b: Int) = a + b 

The following diagram shows the syntax of a Scala anonymous function:

As we discussed with the add() function in the previous section, it is a normal Scala function.

We can write the same function as an anonymous function, as shown here:

scala> (a: Int, b: Int) => a + b 
res0: (Int, Int) => Int = <function2> 

Here, we have created an anonymous function of type Int, Int) => Int. It clearly explains what the inputs are and what the output of this function is: