10.27. Tuples, for When You Just Need a Bag of Things
Problem
You want to create a small collection of heterogeneous elements.
Solution
A tuple gives you a way to store a group of heterogeneous items in a container, which is useful in many situations.
Create a tuple by enclosing the desired elements between parentheses. This is a two-element tuple:
scala> val d = ("Debi", 95)
d: (String, Int) = (Debi,95)Notice that it contains two different types. The following example shows a three-element tuple:
scala>case class Person(name: String)defined class Person scala>val t = (3, "Three", new Person("Al"))t: (Int, java.lang.String, Person) = (3,Three,Person(Al))
You can access tuple elements using an underscore construct:
scala>t._1res1: Int = 3 scala>t._2res2: java.lang.String = Three scala>t._3res3: Person = Person(Al)
I usually prefer to assign them to variables using pattern matching:
scala> val(x, y, z) = (3, "Three", new Person("Al"))
x: Int = 3
y: String = Three
z: Person = Person(Al)A nice feature of this approach is that if you don’t want all of
the elements from the tuple, just use the _ wildcard character in place of the elements
you don’t want:
scala>val (x, y, _) = tx: Int = 3 y: java.lang.String = Three scala>val (x, _, _) = tx: Int = 3 scala>val (x, _, z) = tx: Int = 3 z: Person = Person(Al)
A two-element tuple is an instance of the Tuple2 class, and a tuple with three elements
is an instance of the Tuple3 class. (More on this in the Discussion.) As shown earlier, you ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access