In terms of Array, when no initial values are given, new is required, along with an explicit type:
val ary = new Array[Int](5)
But for List:
val list1 = List[Int]() // "new" is not needed here.
When I add new, an error occurs:
scala> val list = new List[Int]()
<console>:7: error: class List is abstract; cannot be instantiated
       val list = new List[Int]()
Why does this happen?
Following are the point of difference between lists and array in Scala: Lists are immutable whereas arrays are mutable in Scala. Lists represents a linked list whereas arrays are flat.
Sequences provide a method apply() for indexing, ranging from 0 up to the length of the sequence. Seq has many subclasses including Queue, Range, List, Stack, and LinkedList. A List is a Seq that is implemented as an immutable linked list.
Lists are mutable(values can be changed) whereas tuples are immutable(values cannot be changed).
Specific to Scala, a list is a collection which contains immutable data, which means that once the list is created, then it can not be altered. In Scala, the list represents a linked list. In a Scala list, each element need not be of the same data type.
Using new always means you're calling a constructor.
It seems like there's some confusion about the difference between classes and companion objects.
scala> new Array[Int](5)
res0: Array[Int] = Array(0, 0, 0, 0, 0)
scala> Array[Int](5)
res1: Array[Int] = Array(5)
In the first expression, Array refers to the type, and you're calling a constructor.
The second expression desugars to Array.apply[Int](5), and Array refers to the companion object.
You can't write new List because, as the error and the doc says, List is abstract.
When you write List(5), you're calling the apply method on List's companion object.
scala> List[Int](5)
res2: List[Int] = List(5)
List doesn't have a constructor you can call because List is abstract. List is abstract because it's a cons list, so a List instance can either be cons and nil (or, as the Scala library calls them, :: and Nil).
But you can call the :: constructor if you really want to.
scala> new ::('a', new ::('b', Nil))
res3: scala.collection.immutable.::[Char] = List(a, b)
                        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