1. Overview
Arrays are mutable collections of the same type of values. We can access the elements of an array using indices. However, we cannot change its length.
In this tutorial, we’ll discuss various approaches to initializing an array in Scala.
2. Using the new Keyword
The new keyword creates a new array in the memory and initializes all the elements to their default values.
Thus, we can declare an array using the new keyword and the Array instance constructor. Additionally, we specify the type of the elements along with the size:
var array = new Array[Int](4)
Here, we’ve declared the type of array as Int, and its size is 4. This means that all the elements of array are initialized to 0 which is the default integer value:
assert(array(0) == 0)
assert(array.length == 4)
Similarly, if we declare a String type of array, all of its elements would be initialized to null:
var stringArray = new Array[String](3)
assert(stringArray(1) == null)
3. Passing Values to the Constructor
The object Array in Scala provides various utility methods to operate on array elements.
We can use the Array constructor to initialize an array with predefined values. Consequently, it returns an array whose length is equal to the number of elements and the type is same as that of the elements we passed:
var stringArray = Array("This", "is", "a", "string", "array")
assert(stringArray.length == 5)
assert(stringArray(1) == "is")
Here, we’ve passed 5 elements of the type String to the Array constructor. So, it’s a String array of length 5.
4. Using the Array.fill() Method
The fill() method of object Array returns an array of specified size. Also, it fills the array with the elements resulting from the operation that we perform on those elements:
var randomDoubleArray = Array.fill(4) { math.random }
assert(randomArray.length == 4)
Here, the fill() method fills randomDoubleArray with 4 random numbers of type double. The math.random() method returns a double value between 0.0 and 1.0.
Similarly, we can also initialize an array with some random integer values:
randomIntArray = Array.fill(4) { Random.nextInt(4) }
5. Using a Collection with Splat Operator
We can use a predefined Collection to initialize an array. Most importantly, we can use the splat operator for copying all the elements of a collection to the array:
var list = List(1, 2, 3, 4)
var array = Array[Int](list: _*)
assert(array(1) == list(1))
assert(array.length == 4)
Here, the splat operator copies all the elements of list into array. Hence, the length of array is also set to 4. Moreover, since list is made up of integers, we should declare the array type as Int. Otherwise, it will throw a type mismatch error at runtime.
6. Using the List.toArray Method
If we don’t want to use the splat operator, we can use another way to initialize an array with the collection elements. We can use the toArray method of the class List to initialize an array with the elements of the List.
The toArray method converts a collection into an array. Also, the length of the array is equal to the size of the list:
var list = List(1, 2, 3, 4)
var array = list.toArray
assert(array.length == 4)
assert(array(3) == 4)
Here, the method toArray returns an Int array filled with 4 elements. Moreover, it preserves the sequence of the elements.
7. Using the Array.range() Method
The range() method of object Array is used to create and initialize an array of integers. It returns an array of sequential integers in the specified range. Moreover, it’s an overloaded method.
Let’s see the first overloaded version of the range() method:
def range(start: Int, end: Int): Array[Int]
The range() method essentially accepts two parameters – the start value of the range and the end value of the range which is exclusive:
array = Array.range(1, 10)
assert(array.length == 9)
assert(array(8) == 9)
In the above example, the first value, 1, is the start of the range while the second value, 10, is the end of the range. We must note that the array will not include the end value 10. In other words, it returns an array of values ranging from 1 to 9.
By default, the difference between each consecutive element is 1. What if we want to have an array of even or odd numbers? The overloaded version of range() accepts a third parameter – step:
def range(start: Int, end: Int, step: Int): Array[Int]
The step signifies the interval between two consecutive elements of an array. As a result, the range() method returns an array having a difference between successive numbers equal to step.
We can now initialize an array of the first five even numbers:
var array = Array.range(0, 10, 2)
assert(array.length == 5)
assert(array(4) == 8)
Here, the value of step is 2. So it returns an array of five even numbers starting from 0 to 8.
7.1. Initializing an Array in Descending Order
On the other hand, if we need to initialize an array in descending order, we can pass a negative value of step with start value greater than end:
var array = Array.range(10, 0, -2)
assert(array.length == 5)
assert(array(4) == 2)
Here, the array will start with 10, and end with 2. Again, we must remember that 0 will not be included in the resulting array.
7.2. Initializing an Array of Negative Numbers
Finally, we can also initialize an array of negative numbers if we pass start as greater than end and the step value as negative:
var array = Array.range(0, -10, -2)
assert(array.length == 5)
assert(array(4) == -8)
The above code creates an array of negative numbers in descending order starting from 0 to -8 with step value 2.
There are certainly more ways of initializing an array by making a copy of an existing array.
8. Conclusion
In this article, we’ve seen various approaches for initializing an array.
As always, the complete code samples for this article can be found over on GitHub.