Introduction

Whereas Chapter 10 covers collections in general, this chapter provides recipes that are specific to the following collection types:

  • List

  • Array (and ArrayBuffer)

  • Map

  • Set

It also provides a few recipes for special-purpose collections like Queue, Stack, Range, and Stream. The following paragraphs provide a brief introduction to the List, Array, Map, and Set classes.

List

If you’re coming to Scala from Java, you’ll quickly see that despite their names, the Scala List class is nothing like the Java List classes, such as the popular Java ArrayList. The Scala List class is immutable, so its size as well as the elements it refers to can’t change. It’s implemented as a linked list, and is generally thought of in terms of its head, tail, and isEmpty methods. Therefore, most operations on a List involve recursive algorithms, where the algorithm splits the list into its head and tail components.

Array (and ArrayBuffer)

A Scala Array is an interesting collection type. The Scaladoc for the Array class states, “Arrays are mutable, indexed collections of values.” The class is mutable in that its elements can be changed, but once the size of an Array is set, it can never grow or shrink.

Although the Array is often demonstrated in Scala examples, and often shows up in the Scala API and third-party APIs, the recommendation with Scala 2.10.x is to use the Vector class as your “go to” immutable, indexed sequence class, and ArrayBuffer as your mutable, indexed sequence of choice. In keeping with ...

Get Scala Cookbook 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.