What's the difference between :: and ::: in Scala

后端 未结 2 358
生来不讨喜
生来不讨喜 2021-01-30 01:31
val list1 = List(1,2)
val list2 = List(3,4)

then

list1::list2 returns:

List[Any] = List(List(1, 2), 3, 4)

list1:::list2 returns:

Lis         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-30 02:02

    In general:

    • :: - adds an element at the beginning of a list and returns a list with the added element
    • ::: - concatenates two lists and returns the concatenated list

    For example:

    1 :: List(2, 3)             will return     List(1, 2, 3)
    List(1, 2) ::: List(3, 4)   will return     List(1, 2, 3, 4)
    

    In your specific question, using :: will result in list in a list (nested list) so I believe you prefer to use :::.

    Reference: class List int the official site

提交回复
热议问题