CSnerd
CSnerd

Reputation: 2239

Difference between Array and List initialization in Scala

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?

Upvotes: 8

Views: 2923

Answers (2)

Chris Martin
Chris Martin

Reputation: 30756

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)

Upvotes: 13

bb94
bb94

Reputation: 1304

First off, List is abstract, so it can't be instantiated.

Second, you're using the wrong method for List. List.apply initializes a list with the elements from the parameters. You're looking for List.fill (though you're better off initializing its elements at once).

Upvotes: 0

Related Questions