2

I know that Scala List can be created as :

val l = List(1,2,3) 

What goes on under the hood when the above statement is executed ? Is the apply method called here ?

Per the scala documentation : For sequences, apply is positional indexing http://docs.scala-lang.org/overviews/collections/seqs.html

So , are there 2 apply methods , one for positional indexing & another as the factory method for object creation ?

0

1 Answer 1

6

This invocation actually calls the apply method on the companion object to the List class.

Many scala classes have a companion object, which is a singleton object with the same name as the class. Defining methods on this companion object, is the scala equivalent of java's static methods. It is very common for these companion objects to have one or more apply methods that are used as constructor/factory functions to create an instance of the class. In this case the List object has a method that takes a variable number of arguments of the same type, and creates a List of those objects.

In fact, if you define a case class, scala will automatically define a companion object that, among other things, includes and apply method that takes the same arguments as the case class's constructor, which is why you don't need to use new when constructing case classes.

The list instance also has an apply method, which is used to index into the list, but since it is defined on the List class it only applies to instances of the class, not the object List itself.

Sign up to request clarification or add additional context in comments.

2 Comments

I was able to see the apply method in the companion object to List class, where can i see the instance apply method ?
scala-lang.org/api/current/scala/collection/immutable/… in the scaladocs, the class and the companion object are seperate pages, but there is a link to other in the top right.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.