scala------------:: , +:, :+, :::, +++的区别

4种操做符的区别和联系

  • :: 该方法被称为cons,意为构造,向队列的头部追加数据,创造新的列表。用法为 x::list,其中x为加入到头部的元素,不管x是列表与否,它都只将成为新生成列表的第一个元素,也就是说新生成的列表长度为list的长度+1(btw, x::list等价于list.::(x))java

  • :++: 二者的区别在于:+方法用于在尾部追加元素,+:方法用于在头部追加元素,和::很相似,可是::能够用于pattern match ,而+:则不行. 关于+::+,只要记住冒号永远靠近集合类型就OK了。es5

  • ++ 该方法用于链接两个集合,list1++list2spa

  • ::: 该方法只能用于链接两个List类型的集合scala

具体示例

scala> "A"::"B"::Nil
res0: List[String] = List(A, B)

scala> "A"+:"B"+:Nil
res1: List[String] = List(A, B)

scala> Nil:+"A":+"B"
res2: List[String] = List(A, B)

scala> res0 ++ res1
res3: List[String] = List(A, B, A, B)

scala> res0 ::: res1
res4: List[String] = List(A, B, A, B)

scala> res0 :: res1
res5: List[java.io.Serializable] = List(List(A, B), A, B)
相关文章
相关标签/搜索