Higher-Order Functions
- 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
How to be productive with Scala functions that use or return functions.
Topics in This ChapterL1
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 ThereturnExpression
Exercises
Scala mixes object orientation with functional features. In a functional programming language, functions are first-class citizens that can be passed around and manipulated just like any other data types. This is very useful whenever you want to pass some action detail to an algorithm. In a functional language, you just wrap that detail into a function that you pass as an argument. In this chapter, you will see how to be productive with functions that use or return functions.
Highlights of the chapter include:
Functions are “first-class citizens” in Scala, just like numbers.
You can create anonymous functions, usually to give them to other functions.
A parameter that is a function specifies behavior that should be executed later.
Many collection methods take function parameters, applying a function to the values of the collection.
There are syntax shortcuts that allow you to express function parameters in a way that is short and easy to read.
You can create functions that operate on blocks of code and look much like the built-in control statements.
12.1 Functions as Values
In Scala, a function is a first-class citizen, just like a number. You can store a function in a variable:
import scala.math.* val num = 3.14 val fun = ceil
This code setsnumto3.14andfunto theceilfunction.
When you try this code in the REPL, the type ofnumis, not surprisingly,Double. The type offunis reported asDouble => Double,也就是一个函数接收一个d returning aDouble.
What can you do with a function? Two things:
Call it.
Pass it around, by storing it in a variable or giving it to a function as a parameter.
Here is how to call the function stored infun:
fun(num) // 4.0
As you can see, the normal function call syntax is used. The only difference is thatfunis avariable containing a function, not a fixed function.
Here is how you can givefunto another function:
Array(3.14, 1.42, 2.0).map(fun) // Array(4.0, 2.0, 2.0)
Themapmethod accepts a function, applies it to all values in an array, and returns an array with the function values. In this chapter, you will see many other methods that accept functions as arguments.