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:
Scala
Scala
Product2[+T1, +T2] extends ProductHere, 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:
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 :
Nidhi 24
// 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:
Hence, Iteration is easily done here.
List(Nidhi, Nisha, Preeti)