O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

Stay ahead with the world's most comprehensive technology and business learning platform.

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

Start Free Trial

No credit card required

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) {
  println(price)
 }

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 ...

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

Start Free Trial

No credit card required