简体   繁体   中英

Why does scala convert Seq to List?

> 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?

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.

The default implementation for Seq is a List as mentioned in scaladoc here:

Seq Object

Which says

This object provides a set of operations to create Seq values. The current default implementation of a Seq is a List.

When calling Seq(3,4) you actually invoke Seq.apply(3,4) which builds a sequence of two elements as a List underneath.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM