Learn Scala 3 Fast: Tuples

Before we get into the following lessons on sequence classes, it will help if we take a first look at tuples.

A tuple is a heterogeneous collection of elements, which means that a tuple can contain different types of elements. For instance, this is a tuple that contains an Int and a String:

val t = (1, "yo")

Similarly, this is a tuple that contains an Int, String, Char, and Double:

val t = (1, "1", '1', 1.1)

I didn’t mention it previously, but you create a Char (character) by putting it inside single-quotes.

As shown, you create a tuple by putting parentheses around the elements you want inside it. Like the sequence classes you’re about to see, a tuple can hold as many elements as you need, though I typically use it for small collections like these.

A tuple is also an immutable data structure, meaning that its elements can’t be changed and its size can’t be changed.

Accessing tuple elements

A tuple works like a sequence in that the elements are stored in the order you place them in. In Scala 3 you access tuple elements by their index number. For instance, given this tuple:

val t = (42, "fish")

you access its elements as t(0) and t(1):

t(0)     // 42
t(1)     // "fish"

You can also determine how many elements are in a tuple like this:

t.size   // 2

We won’t be using this functionality just yet, but they are good points to know.

The importance of tuples

In terms of these lessons, the important part about tuples is that we need to see them now because they’re used in the following lessons on sequences.

In the longer term, tuples are important because they can be used in other ways!

Exercises

The exercises for this lesson are available here.