Scala | Product2

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 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
          
    }
}

chevron_right


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 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
          
    }
}

chevron_right


Output:

List(Nidhi, Nisha, Preeti)

Hence, Iteration is easily done here.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.