Open In App
Related Articles

Scala | Tuple

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Tuple is a collection of elements. Tuples are heterogeneous data structures, i.e., is they can store elements of different data types. A tuple is immutable, unlike an array in scala which is mutable. An example of a tuple storing an integer, a string, and boolean value.

val name = (15, "Chandan", true)

Type of tuple is defined by, the number of the element it contains and datatype of those elements. 

For Example:

// this is tuple of type Tuple3[ Int, String, Boolean ] 
val name = (15, "Chandan", true)

Let N be the number of elements in a tuple. Scala currently is limited to 22 elements in a tuple, that is N should be, 1<=N<=22 , the tuple can have at most 22 elements, if the number of elements exceeds 22 then this will generate an error. However we can use nested tuples to overcome this limit (Note that a tuple can contain other tuples)

Operations on tuple
  1. Access element from tuple: Tuple elements can be accessed using an underscore syntax, method tup._i is used to access the ith element of the tuple. Example : 

Scala

// Scala program to access
// element using underscore method
 
// Creating object
object gfg
{
    // Main method
    def main(args: Array[String])
    {
 
        var name = (15, "chandan", true)
 
        println(name._1) // print 1st element
        println(name._2) // print 2nd element
        println(name._3) // print 3st element
    }
}

                    
  1. Pattern matching on tuples : Pattern matching is a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts. Example : 

Scala

// Scala program of pattern matching on tuples
 
// Creating object
object gfg
{
    // Main method
    def main(args: Array[String])
    {
        var (a, b, c) = (15, "chandan", true)
        println(a)
        println(b)
        println(c)
    }
}

                    
  1. Here, in above example var (a, b, c)= (15, “chandan”, true) expression assign a = 15, b = “chandan”, c = true.
  2. Iterating over a tuple : To iterate over tuple, tuple.productIterator() method is used. Example : 

Scala

// Scala program to iterate over tuples
// using productIterator method
 
// Creating object
object gfg
{
    // Main method
    def main(args: Array[String])
    {
        var name = (15, "chandan", true)
         
        // The foreach method takes a function
        // as parameter and applies it to
        // every element in the collection
        name.productIterator.foreach{i=>println(i)}
    }
}

                    
  1. Converting tuple to string: Converting a tuple to a string concatenates all of its elements into a string. We use the tuple.toString() method for this. Example : 

Scala

// Scala program to convert tuple element to String
 
// Creating object
object gfg
{
    // Main method
    def main(args: Array[String])
    {
        val name = (15, "chandan", true)
         
        // print converted string
        println(name.toString() )
    }  
}

                    
  1. Swap the elements of tuple: Swapping the element of a tuple we can use tuple.swap Method. Example : 

Scala

// Scala program to swap tuple element
 
// Creating object
object gfg
{
    // Main method
    def main(args: Array[String])
    {
        val name = ("geeksforgeeks","gfg")
         
        // print swapped element
        println(name.swap)
    }
}

                    

In Scala, a tuple is an ordered collection of values, which can be of different types. Tuples are immutable, meaning that their values cannot be changed once they are created.

Here’s an example code that demonstrates how to use a tuple:

Scala

object TupleExample {
  def main(args: Array[String]): Unit = {
    val tuple1 = (1, "hello", 3.14)
    val tuple2 = ("world", 42)
 
    println(tuple1)
    println(tuple2)
 
    println(tuple1._2)
    println(tuple2._1)
  }
}

                    

Output
(1,hello,3.14)
(world,42)
hello
world

In this example, we create two tuples using parentheses to enclose the values. The first tuple contains an integer, a string, and a floating-point number, while the second tuple contains a string and an integer. We print out the tuples using the println() method, which displays the values in parentheses separated by commas.

To access the values inside a tuple, we can use the _n notation, where n is the index of the value (starting from 1). For example, tuple1._2 returns the second element of the first tuple, which is the string “hello”.

Tuples are useful when you need to group together multiple values that are related in some way, but that do not warrant creating a new class or data structure. They provide a simple and efficient way to work with small collections of values in a type-safe manner.

However, tuples can become unwieldy and difficult to work with when they contain a large number of values or when the values have complex types. In such cases, it may be better to create a new class or data structure that encapsulates the values and provides more meaningful methods and operations.

Advantages of Tuples in Scala:

  1. Tuples are a convenient way to store and retrieve a small number of related values without having to create a custom class or data structure.
  2. Tuples can be used in pattern matching and other functional programming constructs in Scala, making them a versatile tool for working with data.
  3. Tuples are immutable, which means that their values cannot be changed once they are created. This makes them suitable for use in functional programming
  4. and other contexts where immutability is important.


Disadvantages of Tuples in Scala:

  1. Tuples can become unwieldy and difficult to work with when they contain a large number of values or when the values have complex types.
  2. Tuples are not as flexible as custom classes or data structures, since they do not provide meaningful methods and operations specific to the domain of the values they contain.


References books:

  1. “Programming in Scala” by Martin Odersky, Lex Spoon, and Bill Venners.
  2. “Scala Cookbook: Recipes for Object-Oriented and Functional Programming” by Alvin Alexander.
  3. “Learning Scala: Practical Functional Programming for the JVM” by Jason Swartz.


Last Updated : 11 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads