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> (1, 2, 3)
res1: (Int, Int, Int) = (1,2,3)
Here is an alternative syntax.
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> 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> "key1" -> "value1" res4: (String, String) = (key1,value1)
scala>scala> ("key2", "value2") res5: (String, String) = (key2,value2)
Tuple2
s are used by Scala Map
s, 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> 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> 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.
Tuple
s may never support higher arity.
© Copyright 1994-2024 Michael Slinn. All rights reserved.
If you would like to request to use this copyright-protected work in any manner,
please send an email.
This website was made using Jekyll and Mike Slinn’s Jekyll Plugins.