Tuple of Scala

? Tuple tuple

Tuple is a set of different types of values , enclosed in parentheses.
Such as: val tuple = ("scala",10)
In the scala tuple has the following characteristics:
1. A tuple is an element may contain different types of
index 2. tuple starting from 1, and the index image Array array is started from 0
for Elements of tuples can be accessed using _1, _2…, such as

object Tuple {
  def main(args: Array[String]): Unit = {
    val tuple = (100,"spark","scala")
    println(tuple._1)  // 100
    println(tuple._2)  // spark
    println(tuple._3)  // scala
  }
}

Operation result:
Insert picture description here
You can also use pattern matching to get the elements in the tuple:

object Tuple {
object Tuple {
  def main(args: Array[String]): Unit = {
    val tuple = (100,"spark","scala")
    println(tuple._1)  // 100
    println(tuple._2)  // spark
    println(tuple._3)  // scala
    println("==============")
    val (a,b,c) = tuple
    println(a)
    println(b)      //1
    println(c)
    println("==============")
    val (a1,b1,_) = tuple
    println(a1)     //2
    println(b1)
   println("===============")
    val a2,b2 = tuple
    println(a2)     //3
    println(b2)
  }
}

Note 1: The variables we defined (1,2,3) can be matched according to the pattern (100, "spark", "scala") and the elements in it one-to-one
Note 2: You can match several individual elements, not The elements that need to be matched can be replaced with _ placeholders.
Note 3: If the brackets are removed, it becomes a few variables to match the entire tuple
Insert picture description here

Published 14 original articles · Like1 · Visits 684

Guess you like

Origin blog.csdn.net/qq_33891419/article/details/103498625