Home »
Scala
Tuples in Scala
By IncludeHelp Last updated : November 15, 2024
Scala Tuples
A tuple is a data structure that has multiple elements. The elements of Scala tuples may or may not be the same data type.
The Scala tuples are immutable, i.e the objects of different type can be stored in the tuple but the value of these objects cannot be changed. The maximum number of miscellaneous elements that a tuple can have is twenty-two.
Defining a Tuple
You can easily use tuples in your scala program for usage. The syntax for defining a tuple:
val tuple_name = (data1, data2, data3, ...);
Defining a Tuple Using Tuple Class
This is a shortcut way of defining a tuple. You can define a tuple by mentioning its tuple class, the class is simply tuples, where n is the number of elements the tuple has. For example,
val tuple_name = new tuple2(data1, data2);
Defining a Tuple Using -> Operator
There is one more method to define a tuple by using the -> operator:
val tuple_name = 'data1' -> 'data2';
Accessing Elements of a Tuple
The access method for accessing an element of a tuple is quite easy and convenient. To access the element at no. n, you have to type in tuple._n, where the tuple is the name of a tuple and nth element is fetched.
Example
For example, if we need fetch 6th element of the tuple t then we will type t._6 to access it.
object MyClass {
def main(args: Array[String]): Unit = {
val student = ("Ram", 10 ,92.4)
println("Student name : "+student._1+" of the Standard "+student._2+" has scored "+student._3+"%")
}
}
Output
Student name : Ram of the Standard 10 has scored 92.4%
Accessing Variables Using Names
For ease of access, you can optionally assign the elements of a tuple name which can later be used to call them. This method is quite useful when you have a handful of elements in your tuple. Remembering names that are logically matching is easier than remembering the number. For example, a tuple has 5 elements and name is 3 elements. To access name, it is easier to remember the word rather than its sequence.
Example
def student = ("Ram", 16, 76.12)
val(name, age, percent) = getUserInfo;
Tuple Methods
1. tuple.productIterator()
It is used to iterate over the elements of a tuple.
Syntax
tuple.productIterator();
2. tuple.toString()
It is used to concatenate all the elements of the tuple into a string.
Syntax
tuple.toString();
3. tuple.swap()
It is used to swap two elements of a tuple.
Syntax
tuple.swap();
Example code to illustrate methods over a tuple
object MyClass {
def main(args: Array[String]): Unit = {
val student = ("Ram", 10);
student.productIterator.foreach(println);
var tuplestring = student.toString;
println("\nThe concatenated string is"+tuplestring);
val studentswap = student.swap;
println("The swapped tuple is "+studentswap);
}
}
Output
Ram
10
The concatenated string is(Ram,10)
The swapped tuple is (10,Ram)