94
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.

Emre Yazici
  • 10,136
  • 6
  • 48
  • 55
Hesey
  • 4,957
  • 6
  • 31
  • 31

2 Answers2

132

:: 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.

Debilski
  • 66,976
  • 12
  • 110
  • 133
  • For performance reason, is there difference between `::` and `:::` ? – null Jan 27 '15 at 10:27
  • 2
    Performance should be `O(n)` with `n` being the number of elements to prepend. – Debilski Jan 27 '15 at 10:59
  • Correct me if I'm wrong, but isn't this operation an append rather than a prepend? – Janac Meena Mar 12 '19 at 17:26
  • 1
    an example would make it much easier to understand – techkuz Sep 11 '19 at 15:18
  • @JanacMeena, this operation is a prepend, [List](https://www.scala-lang.org/api/2.13.3/scala/collection/immutable/List.html) is immutable-singly-linked: after concatenation the a new head is prepended, referencing the existing list directly: it becomes Aliased/shared in memory. It is very cpu/memory efficient for certain patterns of code. This works due to a subtle thing with infix operators: any ending in ':' are right-associative - they are actually defined as a method on the class to their RIGHT not their left. (https://stackoverflow.com/a/15384749/932359) – Luke Usherwood Sep 20 '22 at 10:48
30

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

Paul T. Rawkeen
  • 3,994
  • 3
  • 35
  • 51
RafaelJan
  • 3,118
  • 1
  • 28
  • 46