You want to pass a function around like a variable, just like you
Int, and other variables around in an
object-oriented programming language.
Use the syntax shown in Recipe 9.1 to define a function literal, and then assign that literal to a variable.
The following code defines a function literal that takes an
Int parameter and returns a value
that is twice the amount of the
that is passed in:
As mentioned in Recipe 9.1, you can think of
=> symbol as a
transformer. In this case, the function transforms
i to an
value that is twice the value of
You can now assign that function literal to a variable:
double is an
instance, just like an instance of a
Int, or other type, but in this case, it’s an
instance of a function, known as a function value.
You can now invoke
double just like
you’d call a method:
Beyond just invoking
like this, you can also pass it to any method (or function) that takes a
function parameter with its signature. For instance, because the
map method of a sequence is a generic
method that takes an input parameter of type
A and returns a type
B, you can pass the
double method into the
map method of an
val list = List.range(1, 5)list: List[Int] = List(1, 2, 3, 4) scala>
list.map(double)res0: List[Int] = List(2, 4, 6, 8)
Welcome to the world of functional ...