Chapter 15. Collections: Tuple, Range, Set, Stack, and Queue

Compared to the previous collection chapters, this chapter covers collection classes that tend to be a little different than your standard sequence and map types.

A tuple is essentially a sequence, but like a class or trait, it can contain any number of different types, as shown in this REPL example:

scala> (1, 2.2, "a", 'a')
val res0: (Int, Double, String, Char) = (1, 2.2, a, a)

Tuples are convenient to use when you just want a container for a series of potentially mixed types like this. Recipe 15.1 demonstrates the use of tuples.

A range is an evenly spaced sequence of whole numbers or characters and is often used in for loops and to populate other collections. Their use is covered in Recipe 15.2.

A set is a collection that contains only unique elements, where uniqueness is determined by the == method of the type the set contains. Because a set only contains unique elements, if you attempt to add duplicate elements to it, the set ignores the request. Scala has both immutable and mutable versions of its base Set implementation and offers additional set classes for other needs, such as having sorted sets. Sets are covered in Recipes 15.3 through 15.5.

A queue is a first-in, first-out data structure, and a stack is a last-in, first-out structure. Scala has both mutable and immutable versions of each type, and they’re demonstrated in Recipes 15.6 and 15.7, respectively.

15.1 Creating Heterogeneous Lists with Tuples

Get Scala Cookbook, 2nd Edition 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.