scala中Tuple简单使用

本文介绍了Scala中Tuple的基本用法,包括Tuple2和Tuple3类型的创建与访问方式,并演示了如何利用zip操作将两个数组组合成Tuple数组。此外,还通过增强for循环展示了如何遍历Tuple数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
  * 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)
    }

  }

}

  

转载于:https://www.cnblogs.com/yxj0728/p/9281701.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值