12 Anonymous Functions
Anonymous functions in Scala are of the following forms:
(x: Int) => x * x //type is: Int => Int, e.g. gets an Int and returns an Int
(x: Int, y: Int) => x + y //type is: (Int, Int) => Int, e.g. gets 2 Ints and returns an Int
Which is basically a “syntactic sugar” for this form:
new Function1[Int ,Int] {
def apply(x: Int): Int = x * x
}
new Function2[Int ,Int ,Int] {
def apply(x: Int, y: Int): Int = x + y
}
Type
The type of the 2nd anonymous function is (Int, Int) => Int
and reads: “A function that map from two integers (Int, Int
) to (=>
) an integer (Int
)”
The method doWithOneAndTwo
expects a parameter of that type, so we can pass (x ,y) => x + y
as a parameter.
Parameter type inference
Note that we were able to drop the type declarations for x and y here, becase the compiler already “knows” that doWithOneAndTwo
expects a function that gets 2 Int parameters, therefore we can omit the type information for the parameters x and y in the second call in the example on the left.
Shorter syntax
Furthermore, there is even a shorter syntax for anonymous functions, (with a limitation that each variable is used exactly once in the body of the function). A place holder is used _
to replace each parameter, the first occurrence of _
stands for the first parameter, the second for the second parameter and so forth.