array

  • This is not just a post about arrays, but also tuples and other Scala structures. I've already written about Scala type inference. Well, let's see what happens when one of the element of an Array[Int]is changed into a Double:

    scala> val mix = Array(1, 2, 3)
    mix: Array[Int] = Array(1, 2, 3)

    scala> val mix = Array(1, 2, 3.3)
    mix: Array[Double] = Array(1.0, 2.0, 3.3)
  • One of the very first data structures used in every language is the array. Scala provides two types of arrays, implemented using the JVM facilities: the Array class and the ArrayBuffer class. The first one is used when the length of the array is known in advance, while the second one provides a dynamically growing type of array.

    Here I'm going to declare a new Array:

    scala> val ary = Array[Int](1, 2, 3)
    ary: Array[Int] = Array(1, 2, 3)
  • 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 objectsin 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 createArray 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))

     


  The Cog In The Machine On Which All Depends