Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Array and List initialization in Scala

Tags:

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?

like image 773
CSnerd Avatar asked Dec 08 '14 04:12

CSnerd


People also ask

What is the difference between Array and list in Scala?

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.

What is difference between list and sequence in Scala?

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.

What is the difference between list and tuple in Scala?

Lists are mutable(values can be changed) whereas tuples are immutable(values cannot be changed).

Is list immutable in Scala?

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.


1 Answers

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)
like image 160
Chris Martin Avatar answered Oct 16 '22 22:10

Chris Martin