Difference between array initialization and list in Scala

In terms of Arraywhen no initial values ​​are given, an newexplicit type is also required :

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 is this happening?

+4
source share
2 answers

Use newalways means that you are calling a constructor.

There seems to be 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)

The first expression Arrayrefers to the type, and you call the constructor.

The second expression is desugars for Array.apply[Int](5), and Arrayrefers to the companion object.

new List, , doc, List .

List(5), apply List .

scala> List[Int](5)
res2: List[Int] = List(5)

List , , List . List , , List cons, nil (, Scala, :: nil)).

::, .

scala> new ::('a', new ::('b', Nil))
res3: scala.collection.immutable.::[Char] = List(a, b)
+8

-, List , .

-, List. List.apply . List.fill ( ).

0

All Articles