Scala Array

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Scala Array

Array is a mutable object that means it can be modified. It is a collection of elements which are of the same types. These elements are associated with an index which is used to access or replace a particular element. In fact, an array is implemented as a number of consecutive memory locations which is indexed by consecutive numbers.

In Scala arrays are objects so there are number of methods associated with them. Basically there are two ways to define an array:

  • First is to specify the total number of elements and then assigns values to the elements .
  • Another specifies all values at once


var i:Array[String] = new Array[String](5)

i is declared as an array of Strings which hold up to five elements. You can also declare array as follows:

var i = new Array[String](5)


If one wants to assign values to individual elements or to get access to individual elements then you can use following command:

i(0) = "hello"; i(1) = "intellipaat"; i(2) = "e" ; i(3) = "learning"; i(4) = "company"


Then it will print intellipaat.

Index of first number = 0

Index of last number = n-1 where n is the number of elements in array.


You can also define array as follows:

var i = Array("hello", "intellipaat")


Then it will print hello



var A = new Array[Array[Int]](3,3)

for (i <- 0 to 2) {

for ( j <- 0 to 2) {

if (i == j)