Scala Array

    Array in Scala

    An array is also handled in Scala as an object:

    val myFirstArrayObject = new Array[Int](2)
    
    myFirstArrayObject(0) = 1
    
    myFirstArrayObject(1) = 2

    The above variable denotes an Array of Integer of Size 2. In place of using a[0] like in another programming language, we have used syntax like a(0). This is syntactic sugar to let us call an object just as if it was a function. Under the hood, the compiler is calling a default method called apply(), taking a single input (an Int in our case) to make it possible.

    An array is a mutable object. It is declared as a val in this example, but still, we can change the value of indexes 0 and 1. val just enforces not to mutate the reference, not the corresponding object.