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)
The List
class is sealed
and abstract
. It has two concreate implementations
Nil
which represents an empty list::[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
).
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