Mike Slinn

Scala Tuples

— Draft —

Published 2014-01-10. Last modified 2014-07-18.
Time to read: 1 minutes.

Tuples are introduced as a special case of case classes. This lecture prepares us for the pattern matching lecture. Tuples will be revisited as a collection container in the Collections Overview lecture of the Intermediate Scala course.

Source code for this lecture may be found in src/main/scala/TupleDemo.scala.

Two Syntaxes

Tuples can be created by wrapping a comma-delimited list of objects in parentheses.

Scala REPL
scala> (1, 2, 3)
res1: (Int, Int, Int) = (1,2,3)

Here is an alternative syntax.

Scala REPL
scala> Tuple3(1, 2, 3)
res2: (Int, Int, Int) = (1,2,3)

The type of these tuples is Tuple3[Int, Int, Int].

Tuples Can Contain Any Types

Tuples do not need to contain homogeneous types.

Scala REPL
scala> val t3a = scala> (1, 2.0, "abc")
t3a: (Int, Double, String) = (1,2.0,abc)
scala> %}val t3b = Tuple3(1, 2.0, "abc") t3b: (Int, Double, String) = (1,2.0,abc)

As you can see from the REPL output, the type of t3a and t3b are Tuple3[Int, Double, String].

Tuples with arity 2, or Tuple2 are probably the most commonly used arity of tuple. You can optionally write instances of Tuple2 using a special syntax, suggesting of an associative key/value pair.

Scala REPL
scala> "key1" -> "value1"
res4: (String, String) = (key1,value1)
scala>scala> ("key2", "value2") res5: (String, String) = (key2,value2)

Tuple2s are used by Scala Maps, as we will see in the next course.

Accessing Tuple Properties

You can reference the nth member of a tuple using a getter method called _n, where n is the one-based index of the element.

Scala REPL
scala> t3._1
res6: Int = 1
scala> %}t3._2 res7: Double = 2.0
scala> %}t3._3 res8: String = abc

Tuples Are Case Classes

Because tuples are implemented as case classes, which were discussed in the Case Classes lecture, so all of the standard case class methods are available. This also means that tuples suffer from the arity 22 limitation.

Scala REPL
scala> t3.copy(_2=4.2)
res9: (Int, Double, String) = (1,4.2,abc)
scala> %}t3.copy(_1=99, _3="aardvark") res10: (Int, Double, String) = (99, 4.2, aardvark)

There are 22 Scaladoc entries for Scala tuples, from Tuple1, Tuple2 through Tuple22. Tuples may never support higher arity.


* indicates a required field.

Please select the following to receive Mike Slinn’s newsletter:

You can unsubscribe at any time by clicking the link in the footer of emails.

Mike Slinn uses Mailchimp as his marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp’s privacy practices.