Arrays in Scala

In Scala, an array is a mutable, indexed sequence of elements of a specific type. While arrays are commonly used, other collection types like Lists or Vectors are often preferred for their immutability and additional features.

object Arrays {
  def main(args: Array[String]): Unit = {
    // Here we create an array 'a' that will hold exactly 5 Ints.
    // By default, an array is zero-initialized, which for Ints means 0s.
    var a = new Array[Int](5)
    println(s"emp: ${a.mkString("[", ", ", "]")}")

    // We can set a value at an index using the
    // array(index) = value syntax, and get a value with array(index).
    a(4) = 100
    println(s"set: ${a.mkString("[", ", ", "]")}")
    println(s"get: ${a(4)}")

    // The length method returns the length of an array.
    println(s"len: ${a.length}")

    // Use this syntax to declare and initialize an array in one line.
    val b = Array(1, 2, 3, 4, 5)
    println(s"dcl: ${b.mkString("[", ", ", "]")}")

    // In Scala, you can't use ... to let the compiler count elements.
    // Instead, you can use the Array.apply method or simply parentheses.
    val c = Array(1, 2, 3, 4, 5)
    println(s"dcl: ${c.mkString("[", ", ", "]")}")

    // Scala doesn't have a direct equivalent to Go's index-based initialization.
    // However, you can achieve similar results using the tabulate method.
    val d = Array.tabulate(5)(i => if (i == 0) 100 else if (i == 3) 400 else if (i == 4) 500 else 0)
    println(s"idx: ${d.mkString("[", ", ", "]")}")

    // Array types are one-dimensional, but you can create multi-dimensional
    // arrays by nesting arrays.
    val twoD = Array.ofDim[Int](2, 3)
    for (i <- 0 until 2) {
      for (j <- 0 until 3) {
        twoD(i)(j) = i + j
      }
    }
    println(s"2d: ${twoD.map(_.mkString("[", ", ", "]")).mkString("[", ", ", "]")}")

    // You can create and initialize multi-dimensional arrays at once too.
    val twoD2 = Array(
      Array(1, 2, 3),
      Array(1, 2, 3)
    )
    println(s"2d: ${twoD2.map(_.mkString("[", ", ", "]")).mkString("[", ", ", "]")}")
  }
}

When you run this Scala program, you’ll see output similar to:

emp: [0, 0, 0, 0, 0]
set: [0, 0, 0, 0, 100]
get: 100
len: 5
dcl: [1, 2, 3, 4, 5]
dcl: [1, 2, 3, 4, 5]
idx: [100, 0, 0, 400, 500]
2d: [[0, 1, 2], [1, 2, 3]]
2d: [[1, 2, 3], [1, 2, 3]]

Note that arrays in Scala are displayed in the form [v1, v2, v3, ...] when printed using mkString method.

In Scala, arrays are mutable and have a fixed size. For more flexibility, consider using other collection types like List or Vector which are immutable and provide additional functional programming features.