Scala Arrays by Code Example

Array is a very basic building block of any programming language. Arrays can be treated as static, sequential and fixed size collection of any type in Scala. One important point to note here is ” Scala Arrays are mutable “.

The Syntax of creating array is a bit different than Java and there are two ways to create array in Scala. Let’s have a look.

When you know the type and size of an array and not sure about what are the exact elements in the array,

new Array[Type](Size of An Array)

For Example,

val arrayOfCars = new Array[String](4)
arrayOfCars(0) = "Audi"
arrayOfCars(1) = "BMW"
arrayOfCars(2) = "Lamborghini"
arrayOfCars(3) = "Mercedes"

You can see from above code that index Scala array starts from 0.

When you know the type and exactly which elements are present in the array,

Array(element 1, element 2,..., element N)

In above example you don’t need to specify the type as it can be inferred directly from the element type.

val arrayOfCars = Array("Audi", "BMW", "Lamborghini", "Mercedes")
Accessing the elements of an Array
  • arr.length: Returns the size of the Scala array
  • arr(n): This will return element at n index, null if no element is available and ArrayIndexOutOfBoundsException if n is more than arr.length - 1
  • arr(n) = value: This will assign a new value to a respective array element

Multi-dimensional Arrays

Syntax for creating multi-dimensional arrays in Scala is also very different. You have to write import Array._ first.

ofDim[T](dim 1, dim 2,..., dim N)

Here is an simple example of Matrix,

package com.backtobazics.arrays

import Array._

object AccessingArrays {
  def main(args: Array[String]) {
    var matrix = ofDim[Int](3, 3)

    for (row <- 0 to 2) {
      for (col <- 0 to 2)
        matrix(row)(col) = row + col
    }

    // Print two dimensional array
    for (row <- 0 to 2) {
      for (col <- 0 to 2) {
        print(" " + matrix(row)(col))
      }
      println()
    }
  }
}

//Output:
// 0 1 2
// 1 2 3
// 2 3 4

Stay tuned for more examples…..!!!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>