September 2015
Intermediate to advanced
250 pages
6h 40m
English
Function values help create more reusable code and eliminate code duplication. But, embedding a piece of code as an argument to a method doesn’t encourage reuse of that code. It’s easy to avoid that duplication—you can create references to function values and therefore reuse them as well. Let’s look at an example.
Let’s create a class Equipment that expects a calculation routine for its simulation. We can send in the calculation as a function value to the constructor:
| FunctionValuesAndClosures/Equipment.scala | |
| | class Equipment(val routine : Int => Int) { |
| | def simulate(input: Int) = { |
| | print("Running simulation...") |
| | routine(input) |
| | } |
| | } |
When we create instances of Equipment, we can pass in a function value ...
Read now
Unlock full access