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

Immutable Collections

In order to promote programming with no side effects, Scala imports the immutable collections by default. One of the simplest immutable collections is the Scala list.

 val​ prices ​=​ List(10, 20, 15, 30, 45, 25, 82)

We talked earlier about internal and external iteratorshere. Scala allows us to iterate over the collections using an external iterator (where you control the iteration) or an internal iterator (where you only provide the action to perform for each element).

So, to print each of the elements in the list we created, we can use either

 for​(price ​<-​ prices) { println(price) }

or

 prices.foreach { price ​=>​ println(price) }

(or the concise form: prices foreach println)

Collections provide a wealth ...

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