In this lesson, you will learn how to us arrays in Scala. Array in Scala works similar to arrays in Java, so let’s go ahead to get started!
We’l cover the following sub-topics
- Declaring an Array
- Array Processing
- Multidimensional Arrays
- Array Concatenation
- Array With Range Function
- Some Useful Array Methods
1. Declaring an Array
As you know, before you can use any variable, you must declare it. Arrays are not exceptions. You can declare an array variable in Scala using the syntax below:
// Method 1 var arr:Array[String] = new Array[String](3) // Method 2 var arr = new Array[String](3)
In these examples, we declare an array names arr, that can hold up to 3 String values.
To access the elements of an array, you can use the index which is zero-based. Examples are given below:
arr(0) = "Kindson"; arr(1) = "Jadon"; arr(2) = "Solace" //Another method var arr = Array("Kindson", "Jadon", "Solace")
So you can use either of the two methods
2. Array Processing
Normally we can process multiple array elements using a loop. In the example below we perform the following operations:
- Print all elements of the array
- Sum all elements of the array
- Find the maximum element in the array
// Program to Demonstrate Array Processing object ArrayProcessing { def main(args: Array[String]): Unit = { val arr = Array(34, 66, 78, 3, 95) //Print all element of the array for (ele <- arr) { println(ele) } //Sum all element of the array var sum: Int = 0 for (ele <- arr) { sum = sum + ele } println(s"The sume is $sum") //Find the maximum element var max = arr(0) for (i <- 1 to (arr.length - 1)) { if (arr(i) > max) { max = arr(i) } } println(s"The maximum number in the array is $max") } }
The program above gives the following output
34 66 78 3 95 The sume is 276 The maximum number in the array is 95
3. Multidimensional Arrays
You can think of multidimensional array as an array of arrays. So we have the elements of the array to be arrays as well. That helps create a grid of table view of elements.
The following syntax declares a 2-dimensional array called myGrid.
var myGrid = ofDim[Int](4,4)
The code above creates an array of 4 elements each being an array of 4 elements
The program below creates a 2-dimensional array using a nested loop and then prints out the elements using another nested loop
// Program to Demonstrate Multidimensional Array Processing object MultidimensionalArray { def main(args: Array[String]): Unit = { var myGrid = ofDim[Int](4,4) //Assign items to grid for (i <- 0 to (myGrid.length -1)) { for (j <- 0 to 3) { myGrid(i)(j) = j } } //Print out grid elements for (i <- 0 to (myGrid.length -1)) { for (j <- 0 to 3) { print(" " + myGrid(i)(j)) } println() } } }
4. Array Concatenation
You can also concatenate two arrays using the concat() method. The concat() method for arrays take the two arrays to be concatenated. The syntax is:
var arr3:Array[String] = concat(arr1, arr2)
The program below illustrates concatenation of two arrays. Then printing out the elements of the concatenated array
// Program to Demonstrate Multidimensional Array Processing object MultidimensionalArray { def main(args: Array[String]): Unit = { var arr1:Array[String] = Array("Jadon", "McMills", "Treasure", "Esther") var arr2:Array[String] = Array("Solace", "Onyx", "Trust", "Praise") var arr3:Array[String] = concat(arr1, arr2) //print the concatenated array for (ele <- arr3) { println(ele) } } }
5. Array With the Range Function
You can use the range() function to generate a sequence of values between a given range. The range() function takes two arguments – start and end. It also takes an optional third argument, step which indicate then difference between subsequent values in the array.
// Program to Demonstrate Array with Range object ArrayWithRange { def main(args: Array[String]): Unit = { var jumpTen:Array[Int] = range(10, 100, 10) var jumpOne:Array[Int] = range(1, 10) //print the first array println("Now Printing element of JumpTen...") for (ele <- jumpTen) { println(ele) } //print the second array println("Now Printing element of JumpOne...") for (ele <- jumpOne) { println(ele) } } }
I recommend you run the program yourself and see the output. Leave a comment below if you have challenges.
6. Useful Array Methods
The table below provides a list of some useful array methods.
| SN | Methods and Description |
|---|---|
| 1 | def apply( x: T, xs: T* ): Array[T] – Creates an array of T objects, where T can be any data type |
| 2 | def concat[T]( xss: Array[T]* ): Array[T] – Concatenates all arrays into one single array. |
| 3 | def copy( src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int ): Unit – Copy one array to another. Equivalent to System.arraycopy(src, srcPos, dest, destPos, length) in Java |
| 4 | def empty[T]: Array[T] – Returns an array of length 0 |
| 5 | def iterate[T]( start: T, len: Int )( f: (T) => T ): Array[T] – Returns an array containing repeated applications of a function to a start value. |
| 6 | def fill[T]( n: Int )(elem: => T): Array[T] – Returns an array that contains the results of some element computation a number of times. |
| 7 | def fill[T]( n1: Int, n2: Int )( elem: => T ): Array[Array[T]] – Returns a two-dimensional array that contains the results of some element computation a number of times. |
| 8 | def iterate[T]( start: T, len: Int)( f: (T) => T ): Array[T] – Returns an array containing repeated applications of a function to a start value. |
| 9 | def ofDim[T]( n1: Int ): Array[T] – Creates array with specified dimensions. |
| 10 | def ofDim[T]( n1: Int, n2: Int ): Array[Array[T]] – Creates a 2-dimensional array |
| 11 | def ofDim[T]( n1: Int, n2: Int, n3: Int ): Array[Array[Array[T]]] – Creates a 3-dimensional array |
| 12 | def range( start: Int, end: Int, step: Int ): Array[Int] – Returns an array that contains equally spaced values in some integer interval. |
| 13 | def range( start: Int, end: Int ): Array[Int] – Returns an array containing a sequence of increasing integers in a range. |
| 14 | def tabulate[T]( n: Int )(f: (Int)=> T): Array[T] – Returns an array that contains values of a given function over a range of integer values starting from 0. |
| 15 | def tabulate[T]( n1: Int, n2: Int )( f: (Int, Int ) => T): Array[Array[T]] – Returns a two-dimensional array that contains values of a given function over ranges of integer values starting from 0. |