␡
- 12.1 Functions as Values
- 12.2 Anonymous Functions
- 12.3 Parameters That Are Functions
- 12.4 Parameter Inference
- 12.5 Useful Higher-Order Functions
- 12.6 Closures
- 12.7 Interoperability with Lambda Expressions
- 12.8 Currying
- 12.9 Methods for Composing, Currying, and Tupling
- 12.10 Control Abstractions
- 12.11 Nonlocal Returns
- Exercises
This chapter is from the book
12.2 Anonymous Functions
In Scala, you don’t have to give a name to each function, just like you don’t have to give a name to each number. Here is an anonymous function:
(x: Double) => 3 * x
This function multiplies its argument by 3.
Of course, you can store this function in a variable:
val triple = (x: Double) => 3 * x
That’s just as if you had used a def:
def triple(x: Double) = 3 * x
But you don’t have to name the function. You can just pass it to another function:
Array(3.14, 1.42, 2.0).map((x: Double) => 3 * x) // Array(9.42, 4.26, 6.0)
Here, we tell the map method: “Multiply each element by 3.”