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

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.