Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the Seq shorthand for Scala actually work?

Tags:

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?

like image 806
More Than Five Avatar asked Apr 05 '18 09:04

More Than Five


1 Answers

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.

like image 200
SCouto Avatar answered Sep 23 '22 12:09

SCouto