Scala Product2
Product2是Scala的一个特性,它是两个元素的笛卡尔乘积。在构建类中,它可以被认为是两个元素的元组。这里的线性超类型是Product、Equals、Any,这里的子类是Tulple2。Product2扩展了Product,如下所示。
Product2[+T1, +T2] extends Product
这里,T1和T2是元素的类型。
现在,让我们看看一些例子。
例子:
// 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
这里,_1是上述产品的第一个元素的扩展,_2是产品的第二个元素的扩展。
例子:
// 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)
因此,迭代在这里很容易完成。
极客教程