4種操作符的區(qū)別和聯(lián)系
- :: 該方法被稱為cons,意為構(gòu)造,向隊(duì)列的頭部追加數(shù)據(jù),創(chuàng)造新的列表。用法為 x :: list,其中 x 為加入到頭部的元素,無(wú)論 x 是列表與否,它都只將成為新生成列表的第一個(gè)元素,也就是說(shuō)新生成的列表長(zhǎng)度為 list 的長(zhǎng)度 +1 ( btw, x :: list 等價(jià)于 list.::(x) )
- :+ 和 +:兩者的區(qū)別在于:+ 方法用于在尾部追加元素,+:方法用于在頭部追加元素,和 ::很類似,但是 :: 可以用于 pattern match ,而 +: 則不行. 關(guān)于 +: 和 :+ ,只要記住冒號(hào)永遠(yuǎn)靠近集合類型就OK了。
-
++該方法用于連接兩個(gè)集合,list1 ++ list2
-:::該方法只能用于連接兩個(gè)List類型的集合
具體示例
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)