Why Array(100) is not a new Array(100)?
Sometimes Scala can cause you an excruciating confusion, even with the simplest constructs. Would you be able to answer the title question? Why Array(100) is not a new Array(100)?
I’ve already scraped the surface of companion objects in another post. Companion objects happen to be the reason of the difference between Array(100) and new Array(100). The first translates into a call to Array.apply(100), which is a call to the apply() method of the object Array, the companion of the Array class. As is customary to Scala, the apply() method of a companion object instantiates its class. However the set of parameters is not forced to be the same in length, types of meaning. Actually it happens that the apply() method takes a variable-length list of object to be put inside the newly create Array instance. So:
scala> val a1 = Array(100)
a1: Array[Int] = Array(100)
is equivalent to:
scala> val a2 = new Array[Int](1)
a2: Array[Int] = Array(0)
scala> a2(0) = 100
scala> a2
res1: Array[Int] = Array(100)
Much more compact and quick. The real comfort provided by the companion object’ apply() method is:
scala> val a3 = Array(Array(10,20), Array(30,40))
a3: Array[Array[Int]] = Array(Array(10, 20), Array(30, 40))