9.2. Using Functions as Variables

Problem

You want to pass a function around like a variable, just like you pass String, Int, and other variables around in an object-oriented programming language.

Solution

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 Int that is passed in:

(i: Int) => { i * 2 }

As mentioned in Recipe 9.1, you can think of the => symbol as a transformer. In this case, the function transforms the Int value i to an Int value that is twice the value of i.

You can now assign that function literal to a variable:

val double = (i: Int) => { i * 2 }

The variable double is an instance, just like an instance of a String, 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:

double(2)   // 4
double(3)   // 6

Beyond just invoking double 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 Int sequence:

scala> 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 ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.