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 :
// 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) } } |
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) } } |
List(Nidhi, Nisha, Preeti)
Hence, Iteration is easily done here.
Recommended Posts:
- Scala Map
- Set in Scala | Set-2
- Set in Scala | Set-1
- Scala | Either
- Scala Int %(x: Int) method with example
- Scala Set take() method with example
- BitSet in Scala
- Scala Set min() method with example
- Scala Set sum() method with example
- Scala | Variances
- HashSet In Scala
- Scala | REPL
- Scala | Traits
- Scala Stream
- Hello World in Scala
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.



