Tuple. In a Scala tuple we can combine 2 values in a single unit. We can combine a string and an integer with some simple syntax. The tuple is a single variable.
With tuples, we build abstractions over related values. This helps simplify many parts of our Scala programs. A function can return more than 1 value in a tuple.
First example. Here we create 2 tuples, each with 2 items. The tuples have a String and Int. We can access the first and second items in them.
Detail We can access the first and second items from a tuple with the "_1" and "_2" syntax.
Note The first item in a tuple is at index 1, not index 0, and we must use "_1" to get it.
// Create and print two tuples.val identity1 = ("ABC", 10)
val identity2 = ("DEF", 20)
// Get first and second items from a tuple.
val first = identity1._1
val second = identity1._2
Return multiple values. Often in programs we want to return multiple values from a function. Parameters, classes, or tuples may be used. Here we return a tuple from function.
Note The upperName def receives a name String and returns a two-item tuple containing the uppercase name and the original name.
// This def returns a two-item tuple.// ... It uppercases the argument String.def upperName(name: String): (String, String) = (name.toUpperCase(), name)
// Call upperName function with String.
val name = "scala"
val result = upperName(name)
Unpack. We can unpack a tuple in an assignment statement. Here the function returns a tuple with two items in it. We assign the values number1 and number2 to those items.
Tip This syntax immediately unpacks a tuple. This can make a program simpler to read.
// Return a tuple.
def twoNumbers(x: Int): (Int, Int) = (x * 2, x * 4)
// Unpack the tuple returned by the function.val (number1, number2) = twoNumbers(3)
Match. We can use a tuple as the argument of a match construct. We specify values within match cases to require specific values in a tuple.