Open In App

Scala | Product2

Last Updated : 13 May, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

Product2 is a trait in Scala, which is a Cartesian product of two elements. In build-in classes it can be considered as tuple of two elements. The Linear Supertypes here are Product, Equals, Any, and the sub-class here is Tulple2. Product2 extends Product like below:

Product2[+T1, +T2] extends Product

Here, T1 and T2 are the types of the elements.
Now, lets see some examples.
Example :




// Scala program of a trait
// Product2
  
// Creating an object
object GfG
{
  
    // Main method
    def main(args: Array[String]) 
    {
      
        // Applying Produt2 trait and
        // assigning values
        val pro: Product2[String, Int] = ("Nidhi", 24)
          
        // Displays the first element
        println(pro._1)
          
        // Displays the second element
        println(pro._2)
          
    }
}


Output:

Nidhi
24

Here, _1 is the extension for the first element of the product stated above and _2 is the extension for the second element of the product.

Example :




// Scala program of a map
// using trait Product2
  
// Creating an object
object GfG
{
  
    // Main method
    def main(args: Array[String])
    {
      
        // Applying Product2 trait with
        // an iterator
        val x : Iterator[Product2[String, Int]] =
          
        // List of the elements 
        List("Nidhi" -> 24, "Nisha" -> 22, "Preeti" -> 26).iterator
          
        // Calling first types of elements 
        // of the trait Product2 from the
        // List using map method
        val result = x.map(y => y._1).toList
          
        // Displays String types of
        // the list
        println(result)
          
    }
}


Output:

List(Nidhi, Nisha, Preeti)

Hence, Iteration is easily done here.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads