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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.