Scala | Product2
Last Updated :
13 May, 2019
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 :
object GfG
{
def main(args : Array[String])
{
val pro : Product 2 [String, Int] = ( "Nidhi" , 24 )
println(pro. _ 1 )
println(pro. _ 2 )
}
}
|
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 :
object GfG
{
def main(args : Array[String])
{
val x : Iterator[Product 2 [String, Int]] =
List( "Nidhi" - > 24 , "Nisha" - > 22 , "Preeti" - > 26 ).iterator
val result = x.map(y => y. _ 1 ).toList
println(result)
}
}
|
Output:
List(Nidhi, Nisha, Preeti)
Hence, Iteration is easily done here.
Share your thoughts in the comments
Please Login to comment...