In Scala, arrays are defined as special kinds of collections. We use these to store a fixed number of elements of the same data type.
Arrays in Scala are similar in syntax and mutability to arrays in other languages. However, Scala arrays may differ in functionality.
Scala supports both one-dimensional and multi-dimensional arrays. Since Scala arrays are very generic in nature, it is easy to declare them. Mostly, arrays just need an abstract parameter T
for the datatype of the array.
Let’s explore a 1D array in Scala.
The illustration above shows the index and their respective values in the array. The lower bound refers to the zeroth index (first value) in the array. The upper bound refers to the last index (last value) in the array.
var arrayname = new Array[datatype](size)
var myarray = Array(12, 13, 15, 29, 34, 56, 21, 34)
Both of these declarations are valid to declare arrays in scala.
This declaration is very simple and follows the standard array declarations of other languages as far as syntax is concerned.
size
is the total number of elements in the array. datatype
refers to the type of array (Integer, String, Double, etc).
The code below shows how to declare an array, access an individual array item, update an array item, and assign individual values at the required array indices.
object Main extends App {var myarray = Array(12, 13, 15, 29, 34, 56, 21, 34)// printing elements of arrayprintln("Elements of array")for ( n <-myarray ){println(n)}// printing 4th array elementprintln("element at index 4: " + myarray(4))// updating element at array index 4myarray(4) = 59// printing 4th array elementprintln("element at index 4 after updating: " + myarray(4))// Creating a new array by specifying datatype and length// create a string array of 5 elementsvar cities = new Array[String](5)// Adding element in an arraycities(0)="Hong Kong"cities(1)="Tokyo"cities(2)="Islamabad"cities(3)="Cape Town"cities(4) = "New York"println("Displaying array: ")for ( city <-cities ){println(city)}}
Free Resources