Scala Arrays

Jakob Jenkov
Last update: 2014-07-08

In Scala arrays are immutable objects. You create an array like this:

var myArray : Array[String] = new Array[String](10);

First you declare variable var myArray to be of type Array[String]. That is a String array. If you had needed an array of e.g. Int, replace String with Int.

Second you create a new array of Strings with space for 10 elements (10 Strings). This is done using the code new Array[String](10). The number passed in the parentheses is the length of the array. In other words, how many elements the array can contain.

Once created, you cannot change the length of an array.

Accessing Array Elements

You access the elements of an array by using the elements index in the array. Element indexes go from 0 to the length of the array minus 1. So, if an array has 10 elements, you can access these 10 elements using index 0 to 9.

You can access an element in an array like this:

var aString : String = myArray(0);

Notice how you use normal parentheses to enclose the element index, rather than the square brackets [] used in Java.

To assign a value to an array element, you write this:

myArray(0) = "some value";

Iterating Array Elements

You can iterate the elements of an array in two ways. You can iterate the element indexes, or iterate the elements themselves.

Iterate Indexes

The first way is to use a for loop, and iterate through the index numbers from 0 until the length of the array. Here is how:

for(i <- 0 until myArray.length){
    println("i is: " + i);
    println("i'th element is: " + myArray(i));
}

The until keyword makes sure to only iterate until myArray.length - 1. Since array element indexes go from 0 to the array length - 1, this is the appropriate way to iterate the array.

If you had needed i to also take the value of myArray.length in the final iteration, you could have used the to keyword instead of the until keyword. For more details on for loops, see the text
Scala for.

Iterate Elements

The second way to iterate an array is to ignore the indexes, and just iterate the elements themselves. Here is how:

for(myString <- myArray) {
    println(myString);
}

For each iteration of the loop the myString takes the value of the next element in the array. Note that myString is a val type, so you cannot reassign it during the for loop body execution.

Jakob Jenkov

Featured Videos

Java Generics

Java ForkJoinPool

P2P Networks Introduction



















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next