> 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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With