Imagine, for instance, you would like to pair together an identification number (Int
) and a name (String
).
Let's see how to do that in Scala.
By now, you probably have understood that a Tuple is a way to combine two or more types into one. For instance you can combine aInt
and aString
into a tuple(Int, String)
. You can combine up to 22 Types ! ( You can read more whyon here)
The other important aspect is the accessors. For instance, if you have a Tuple(Double, Int, String)
, to access the first element you have to use_1
, the second with_2
, etc…
Tuples are also involved in the concept ofpattern matchingthat we are going to learn more about later.
As a note about good practices: whenever possible, you should use acase class
rather than a Tuple. In the long run, it makes things much easier to manage and maintain.