Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does scala convert Seq to List?

Tags:

scala

> val a:Seq[Integer] = Seq(3,4)
a: Seq[Integer] = List(3, 4)

If Seq is only a trait, why does the compiler / REPL accept it, and does it behave like that for many other traits or even abstract classes?

like image 527
matanster Avatar asked Sep 28 '14 13:09

matanster


People also ask

Is a seq a list Scala?

A Seq is an Iterable that has a defined order of elements. Sequences provide a method apply() for indexing, ranging from 0 up to the length of the sequence. Seq has many subclasses including Queue, Range, List, Stack, and LinkedList. A List is a Seq that is implemented as an immutable linked list.

What is the difference between sequence and list in Scala?

Sequence in Scala is a collection that stores elements in a fixed order. It is an indexed collection with 0 index. List is Scala is a collection that stores elements in the form of a linked list. Both are collections that can store data but the sequence has some additional features over the list.

How do you turn a list into a sequence?

A java list can be converted to sequence in Scala by utilizing toSeq method of Java in Scala. Here, you need to import Scala's JavaConversions object in order to make this conversions work else an error will occur.


1 Answers

It doesn't convert anything.

Seq is a trait, you can't really instantiate it, only mix it in to some class.

Since apply method of the Seq companion object has to return some concrete class instance (that mixes in Seq trait), it returns a List which seems to be a reasonable default.

One situation this can be useful in, is when you need some Seq instance, but don't care about implementation and don't have time to look at the type hierarchy to find a suitable class implementing Seq. Seq(3,4) is guaranteed to give you something that obeys the Seq contract.

like image 144
soulcheck Avatar answered Sep 19 '22 04:09

soulcheck