In Scala, Seq is a trait which corresponds loosely to a List in Java. However, in Scala it is possible to do:
Seq(1, 2, 3)
and get a new List with elements 1,2,3.
But Seq is an abstraction? there is no new
keyword. So how is this magic working?
You can create an object from regular classes in Scala in both ways, with or without the new
keyword. By omitting it you are calling the apply method on the companion object of the class.
Here is an example with a trivial class Foo
class Foo { }
object Foo {
def apply() = new Foo
}
You can both create a Foo object by:
val myFooWNew = new Foo
val myFooWONew = Foo()
If you have a case class, when you define the case class, the companion object and its apply method are created implicitly for you.
case class Bar { }
And you can create the object the same both ways:
val myBarWNew = new Bar
val myBarWONew = Bar()
This is valid with non-abstract classes. Since Seq
is, as you said, a trait, it lacks a constructor, so it's implementation is (roughly) always in the companion object.
In reality, the Seq
construction is a bit more complicated, with GenSeqFactory
and many other classes from inside.
Also there is a List
class which is more like a LinkedList
in Java. There is an awesome answer about Seq
vs List
in Scala here.
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