Arrays in Scala

Array is a collection of similar type values.

Values of an array can be accessed used an index that ranges from zero to (array size -1).

An array can contain values of primitive datatype or objects of a class type.

In Scala programming, you can declare one-dimensional arrays or multi-dimensional arrays.

ADVERTISEMENT

Scala One Dimensional Array

Following is the syntax to declare an Integer Array with an initial size.

var arrayname:Array[Type] = new Array[Type](size)

where

  • arrayname is the identifier to the Array.
  • Type is the datatype or the class type of the elements in the Array.
  • size is the initial size of the array.

You can skip the array type declaration right after the variable name.

var arrayname = new Array[Type](size)

or ignore the type declaration in new array phrase.

var arrayname:Array[Type] = new Array(size)

You can also initialize an Array with elements during its declaration.

var arrayname = Array(element1, element2, .., elementN)