Search code examples
scalacollectionstraitsseq

What concrete datatype is created when I use the Seq[T] constructor?


Scala allows me to instantiate an object that implements the Seq trait directly using this syntax:

val numbers: Seq[Int] = Seq(1, 2, 3)
val names: Seq[String] = Seq("Alice", "Bob", "Charles")
  1. Since Seq is a trait and not a concrete implementation, what data type underlies numbers and names?
  2. What's the best way I could have figured this out for myself?
  3. Is it idiomatic to create a trait object directly?

Thanks!


Solution

  • List is the default implementation. You can easily test this in the Scala REPL:

    scala> val numbers: Seq[Int] = Seq(1, 2, 3)
    numbers: Seq[Int] = List(1, 2, 3)
    
    scala> val names: Seq[String] = Seq("Alice", "Bob", "Charles")
    names: Seq[String] = List(Alice, Bob, Charles)
    

    As far as what is better (creating List or Seq), I think it's about preference. Both options are available, and as far as I know the compiler does not complain when choosing one over the other. I personally always use Seq.