With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

Creating a Higher-Order Function

Continuing with the stock prices example, you’re asked to write a function that will total the prices given in a collection. You figure a simple iteration is sufficient, and you write:

 ​ ​val​ prices ​=​ List(10, 20, 15, 30, 45, 25, 82)
 ​ ​def​ totalAllPrices(prices ​:​ ​List​[​Int​]) ​=​ { ​ prices.foldLeft(0) { (total, price) ​=>​ ​ total + price ​ } ​ }

In the totalAllPrices function, the foldLeft method of the list is used to compute the total in a functional style with pure immutability. You pass a function value to the foldLeft method. This function value accepts two parameters and returns the total of these two parameters. The foldLeft method invokes the function value as many times as the number of elements ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required