8

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?

2 Answers 2

13

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)
Sign up to request clarification or add additional context in comments.

2 Comments

why Array can be initialized by calling a constructor, but List cannot? Why Scala designs something like that?
There isn't really any other way to design a cons list. I've updated my answer with an attempt to explain.
0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.