- 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
12.4 Parameter Inference
When you pass an anonymous function to another function or method, Scala helps you out by deducing types when possible. For example, you don’t have to write
valueAtOneQuarter((x: Double) => 3 * x) // 0.75
Since the valueAtOneQuarter method knows that you will pass in a (Double) => Double function, you can just write
valueAtOneQuarter((x) => 3 * x)
As a special bonus, for a function that has just one parameter, you can omit the () around the argument:
valueAtOneQuarter(x => 3 * x)
It gets better. If a parameter occurs only once on the right-hand side of the =>, you can replace it with an underscore:
valueAtOneQuarter(3 * _)
This is the ultimate in comfort, and it is also pretty easy to read: a function that multiplies something by 3.
Keep in mind that these shortcuts only work when the parameter types are known.
val fun = 3 * _ // Error: Can’t infer types
You can specify a type for the anonymous parameter or for the variable:
3 * (_: Double) // OK val fun: (Double) => Double = 3 * _ // OK because we specified the type for fun
Of course, the last definition is contrived. But it shows what happens when a function is passed to a parameter (which has just such a type).