scala 中::和:::的 +: 与:+的区别

def main(args: Array[String]): Unit = {


  /**
   * 说明
   *  1. 在默认情况下 List 是scala.collection.immutable.List,即不可变
   *  2. 在scala中,List就是不可变的,如需要使用可变的List,则使用ListBuffer
   *  3. List 在 package object scala 做了 val List = scala.collection.immutable.List
   *  4. val Nil = scala.collection.immutable.Nil // List()
   */
  // 创建时,直接分配元素
  val list = List(1, 2, 4)
  // List(1, 2, 4)
  println(list)

  // 空集合
  val nil = Nil
  //List()
  println(nil)

  // 取出list的第二个元素
  println(list(1))

  // 目前list(1,3,4)
  println("----------------list追加元素后的效果-------------------------")
  /**
   * 通过 :+ 和 +: 给list最佳元素,生成新的集合,源集合没有变化
   */
  val list1 = list :+ 5

  // List(1, 2, 4, 5)
  println(list1)
  val list2 = 0 +: list1
  // List(0, 1, 2, 4, 5)
  println(list2)

  println("----------------:: 符号的使用-------------------------")
  /**
   * :: 符号的使用
   */
  val list4 = List(1, 2, 3, "abc")
  //说明 val list5 = 4 :: 5 :: 6 :: list4 :: Nil 步骤
  //1. List()
  //2. List(List(1, 2, 3, "abc"))
  //3. List(6,List(1, 2, 3, "abc"))
  //4. List(5,6,List(1, 2, 3, "abc"))
  //5. List(4,5,6,List(1, 2, 3, "abc"))
  val list5 = 4 :: 5 :: 6 :: list4 :: Nil
  println("list5=" + list5)

  //说明 val list6 = 4 :: 5 :: 6 :: list4 ::: Nil 步骤
  //1. List()
  //2. List(1, 2, 3, "abc")
  //3. List(6,1, 2, 3, "abc")
  //4. List(5,6,1, 2, 3, "abc")
  //5. List(4,5,6,1, 2, 3, "abc")
  val list6 = 4 :: 5 :: 6 :: list4 ::: Nil
  println("list6=" + list6)
  println("注意::和:::的区别!")
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值