Arrays are mutable, indexed collections of values.Array[T] is Scala's representation for Java'sT[].
val numbers = Array(1, 2, 3, 4)val first = numbers(0) // read the first elementnumbers(3) = 100 // replace the 4th array element with 100val biggerNumbers = numbers.map(_ * 2) // multiply all numbers by twoArrays make use of two common pieces of Scala syntactic sugar, shown on lines 2 and 3 of the above example code. Line 2 is translated into a call toapply(Int), while line 3 is translated into a call toupdate(Int, T).
Two implicit conversions exist inscala.Predef that are frequently applied to arrays: a conversion toscala.collection.ArrayOps (shown on line 4 of the example above) and a conversion toscala.collection.mutable.ArraySeq (a subtype ofscala.collection.Seq). Both types make available many of the standard operations found in the Scala collections API. The conversion toArrayOps is temporary, as all operations defined onArrayOps return anArray, while the conversion toArraySeq is permanent as all operations return aArraySeq.
The conversion toArrayOps takes priority over the conversion toArraySeq. For instance, consider the following code:
val arr = Array(1, 2, 3)val arrReversed = arr.reverseval seqReversed : collection.Seq[Int] = arr.reverseValuearrReversed will be of typeArray[Int], with an implicit conversion toArrayOps occurring to perform thereverse operation. The value ofseqReversed, on the other hand, will be computed by converting toArraySeq first and invoking the variant ofreverse that returns anotherArraySeq.
Scala Language Specification, for in-depth information on the transformations the Scala compiler makes on Arrays (Sections 6.6 and 6.15 respectively.)
"Scala 2.8 Arrays" the Scala Improvement Document detailing arrays since Scala 2.8.
"The Scala 2.8 Collections' API" section onArray by Martin Odersky for more information.
The element at given index.
The element at given index.
Indices start at0;xs.apply(0) is the first element of arrayxs. Note the indexing syntaxxs(i) is a shorthand forxs.apply(i).
the index
the element at the given index
ArrayIndexOutOfBoundsExceptionifi < 0 orlength <= i
Clone the Array.
The length of the array
Update the element at given index.
Update the element at given index.
Indices start at0;xs.update(i, x) replaces the ith element in the array. Note the syntaxxs(i) = x is a shorthand forxs.update(i, x).
the index
the value to be written at indexi
ArrayIndexOutOfBoundsExceptionifi < 0 orlength <= i