TuplesIntroduction to ScalaWriting functionsArrays

Arrays

To store many objects of the same type, we can use an array:

scala> val L = Array("CS109", "is", "the", "best")
L: Array[java.lang.String] = Array(CS109, is, the, best)
scala> L.length
res1: Int = 4
scala> L(0)
res2: java.lang.String = CS109
scala> L(3)
res3: java.lang.String = best
Note the type of L. It is not just Array, but Array[java.lang.String]. Array is a parameterized type, where the type parameter indicates the type of the objects stored inside the array.

The elements of the array can be accessed as L(0) to L(L.length-1). Scala uses normal round parentheses to access the elements of an array, not square brackets like Java, C, or Python. Like me, you will probably get this wrong a lot until you get used to it...

An array is a consecutive block of memory that can store a fixed number of objects. This is the same as arrays in Java or C, but completely different from lists in Python: You cannot append elements to an array, or change its length in any way. (We will later meet other data structures where you can do this.)

Above we saw how to create an array when you already know the objects that go in the array. In many cases you want to create an array that is initially empty:

scala> val A = new Array[Int](100)
A: Array[Int] = Array(0, ... 0)
Here, Array[Int] indicates the type of object you want to create, and 100 is the number of elements. When you create an array of numbers, all elements are initially zero. It's different for other arrays:
scala> val B = new Array[String](5)
B: Array[String] = Array(null, null, null, null, null)
Here, the elements of the new array have the special value null, similar to None in Python. This value typically means that a variable has not been initialized yet. Except for the basic numeric types, a variable of any type can have the value null.

Sometimes you may want to create an "empty" array, that is, an array of length zero (perhaps because you want to extend it later using the :+ operator). This is done using:

scala> var a = Array.empty[Int]
a: Array[Int] = Array()

You can use a for-loop to look at the elements of an array one-by-one:

scala> for (i <- L)
     |   println(i)
CS109
is
the
best
This is called "iterating over an array" and is quite similar to the for-loop in Python.

Here is a list of the most important Array-methods.

TuplesIntroduction to ScalaWriting functionsArrays