scala中Tuple简单使用

时间:2023-01-12 23:14:20
/**
  * Tuple简单使用记录
  * 最大22个参数
  */
object TupleUse {

  def main(args: Array[String]): Unit = {
    // 简单Tuple
    val t = ("yxj", 30) // Tuple2
    println(t._1) // 访问Tuple中的数据,从1开始,带上下划线
    println(t._2)

    val student = new Tuple3(1, "yxj", 30) // Tuple3
    println(student)

    //zip操作
    val names = Array("t", "tt", "ttt")
    val ages = Array(10, 20, 30)
    val nameAges = names.zip(ages)
    println(nameAges) // [Lscala.Tuple2;@13deb50e
    println(nameAges.mkString(",")) // (t,10),(tt,20),(ttt,30)

    // 增强for循环
    for ((name, age) <- nameAges) {
      println("name=" + name + ",age=" + age)
    }

    val students = Array((1, "yxj", 30), (2, "yxj2", 32), (3, "yxj3", 33))
    for ((id, name, age) <- students) {
      println("id=" + id + ",name=" + name + ",age=" + age)
    }

  }

}