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

Scala

Scala Problem Overview


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:

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

I saw the book writes that when use :: it also results List[Int] = List(1, 2, 3, 4). My Scala version is 2.9.

Scala Solutions


Solution 1 - Scala

:: prepends a single item whereas ::: prepends a complete list. So, if you put a List in front of :: it is taken as one item, which results in a nested structure.

Solution 2 - Scala

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHeseyView Question on Stackoverflow
Solution 1 - ScalaDebilskiView Answer on Stackoverflow
Solution 2 - ScalaRafaelJanView Answer on Stackoverflow