Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

differences between List(), Array() and new List(), new Array() in Scala

Tags:

scala

I know that when you type:

val list = List(2,3)

you are accessing the apply method of the List object which returns a List. What I can't understand is why is this possible when the List class is abstract and therefore cannot be directly instanciated(new List() won't compile)? I'd also like to ask what is the difference between:

val arr = Array(4,5,6)

and

val arr = new Array(4, 5, 6)
like image 522
user1113314 Avatar asked Dec 12 '22 17:12

user1113314


1 Answers

The List class is sealed and abstract. It has two concreate implementations

  1. Nil which represents an empty list
  2. ::[B] which represents a non empty list with head and tail. ::[B] in the documentation

When you call List.apply it will jump through some hoops and supply you with an instance of the ::[B] case class.

About array: new Array(4, 5, 6) will throw a compile error as the constructor of array is defined like this: new Array(_length: Int). The apply method of the Array companion object uses the arguments to create a new instance of an Array (with the help of ArrayBuilder).

like image 91
EECOLOR Avatar answered May 17 '23 06:05

EECOLOR