Why do I get a List when I create Seq using the following code?
scala> val s = Seq[Int]()
s: Seq[Int] = List()
In fact, Seq is a trait and trait cannot be initialized. What't the magic behind the scene
CodePudding user response:
You called apply
from the Seq
companion object. The implementation of apply
returned a List[Int]
, which is an instance of Seq[Int]
CodePudding user response:
Seq
is a trait, List
is a (default) implementation.
object Seq extends SeqFactory.Delegate[Seq](List)
// ^^^^
https://github.com/scala/scala/blob/v2.13.10/src/library/scala/collection/immutable/Seq.scala#L39
implicitly[List[Int] <:< Seq[Int]] // compiles, i.e. List[Int] is a subtype of Seq[Int]
Seq
is a trait and trait cannot be initialized
Firstly, even if X
is a trait you can instantiate an anonymous class extending the trait: new X {}
. (By the way, List
is also an abstract class.)
Secondly, Seq[Int]()
is desugared into Seq.apply[Int]()
and you refer to not the trait Seq
but its companion object.