What is the reason for creating ::
for List
and is not available for all subclasses Seq
? To give a concrete example:
// :: for pattern matching
def getTail[E](s: Seq[E]): Seq[E] = s match {
case head :: tail => tail
case empty => empty
}
getTail(Seq(1, 2)) // returns List(2) as expected
getTail(Seq()) // returns List() as expected
getTail(Queue(1, 2)) // returns Queue(1, 2), not Queue(2)
getTail(Buffer(1, 2)) // returns ArrayBuffer(1, 2), not ArrayBuffer(2)
// :: for building sequences
1 :: 2 :: 3:: Nil // Creates List(1, 2, 3)
1 :: 2 :: List(3) // same as above
1 :: 2 :: Queue(3) // does not compile. :: is not a method within Queue
All sequences are ordered and have the concepts of "head" and "tail", so why do library collection developers provide ::
up to List
? Why should I use +:
if I want to work with everyone Seq
?
Edit: I understand the performance argument - they gave me it almost every time I asked this question, but I basically disagree with it. Imagine another collection library in which only one has been changed: deletion ::
from List
. What would change?
+:
Nil
, "A" +: "B" +: Nil
.- -
+:
. case head +: tail => println(head)
Seq
. linter , , getTail
.
, , List
, , , +:
. , ::
List
. , ::
.