Arrays are mutable, indexed collections of values.
Array[T]is Scala's representation for Java's
val numbers = Array(1, 2, 3, 4) val first = numbers(0) // read the first element numbers(3) = 100 // replace the 4th array element with 100 val biggerNumbers = numbers.map(_ * 2) // multiply all numbers by two
Arrays 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 to
apply(Int), while line 3 is translated into a call to
Two implicit conversions exist in Predef that are frequently applied to arrays: a conversion to collection.ArrayOps (shown on line 4 of the example above) and a conversion to collection.mutable.ArraySeq (a subtype of collection.Seq). Both types make available many of the standard operations found in the Scala collections API. The conversion to
ArrayOpsis temporary, as all operations defined on
Array, while the conversion to
ArraySeqis permanent as all operations return a
The conversion to
ArrayOpstakes priority over the conversion to
ArraySeq. For instance, consider the following code:
val arr = Array(1, 2, 3) val arrReversed = arr.reverse val seqReversed : collection.Seq[Int] = arr.reverse
arrReversedwill be of type
Array[Int], with an implicit conversion to
ArrayOpsoccurring to perform the
reverseoperation. The value of
seqReversed, on the other hand, will be computed by converting to
ArraySeqfirst and invoking the variant of
reversethat returns another
- See also
- 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 on
Arrayby Martin Odersky for more information.
The element at given index.
Update the element at given index.