A Simple Example

Let’s start with a simple iteration: given a list of stock prices, we’d like to print each price on a separate line.

Initially, the traditional for loop comes to mind, something like this in Java:

 for(int i = 0; i <= prices.size(); i++)

Or is it < instead of <= in the loop condition?

There is no reason to burden ourselves with that. We can just use the for-each construct in Java, like so:

 for(double price : prices)

Let’s follow this style in Scala:

 val prices = List(211.10, 310.12, 510.45, 645.60, 832.33)
 for(price <- prices) {

Scala’s type inference determines the type of the prices list to be List[Double] and the type of price to be Double. The previous style of iteration is often referred ...

Get Functional Programming: A PragPub Anthology 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.