By: | 03 Aug 2016 | Category: Scala Language Basics
Scala provides support for Array data types. In Scala an Array is an instance of the scala.Array class. An Array in Scala is similar to a Java Array. Let’s look at some examples of creating Arrays in Scala.
val array = new Array[Int](2)
Above we create a new Integer array with space for two Int elements. In the above declaration the type of the array is specified in square brackets.
We can assign values to an array element using the syntax.
array(0) = 1
This is different to Java in that we don’t use square brackets. To output the value of an array element we can do:
Scala Iterate Array
Scala provides a number of array methods. One in particular is the foreach method that allows us to pass a function to operate on each element in the Array.
Above we pass the functional literal println to the array foreach method, to output its values.