Parameter Routing

Where it makes sense, you can make function values more concise than you’ve seen so far. Let’s first create an example to find the maximum of an array of values, using the Math.max method to compare two values:

 
val​ largest =
 
(​Integer​.MIN_VALUE /: arr) { (carry, elem) => Math.max(carry, elem)}

In the function value, we’re sending the parameters carry and elem as arguments to the method max to determine which of those two is larger. We use the result of that computation to eventually determine the largest element in the array. As you learned in the previous section, we can use _ to make the function value concise and eliminate the explicit parameters, like so:

 
val​ largest = (​Integer​.MIN_VALUE /: arr) { Math.max(_, ...

Get Pragmatic Scala 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.