Introduction to Scala Array

An array is a mutable object that means it can be modified. It is a collection of elements that are of the same types. These elements are associated with an index that 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.

Enroll yourself in Online Scala training and give a head-start to your career in Scala!

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

  • The first is to specify the total number of elements and then assign values to the elements.
  • Another specifies all values at once

e.g.

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 the 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 the following command:

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

Then it will print intellipaat.
Index of first number = 0
Index of last number = n-1 where n is the number of elements in the array.

You can also define an array as follows:

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

Want to get certified in Scala! Learn Scala from top Scala experts and excel in your career with Intellipaat’s Scala certification!

Then it will print hello

e.g.

var A = new Array[Array[Int]](3,3)
for (i <- 0 to 2) {
for ( j <- 0 to 2) {
if (i == j)
println(A(i)(j))
else
println(A(i)(j))
}
}

Recommended Videos

Leave a Reply

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