Array

final class Array[T](_length: Int) extends Serializable with Cloneable

Arrays are mutable, indexed collections of values. Array[T] is Scala's representation for Java's T[].

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 update(Int, T).

Two implicit conversions exist in scala.Predef that are frequently applied to arrays: a conversion to scala.collection.ArrayOps (shown on line 4 of the example above) and a conversion to scala.collection.mutable.ArraySeq (a subtype of scala.collection.Seq). Both types make available many of the standard operations found in the Scala collections API. The conversion to ArrayOps is temporary, as all operations defined on ArrayOps return an Array, while the conversion to ArraySeq is permanent as all operations return a ArraySeq.

The conversion to ArrayOps takes 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

Value arrReversed will be of type Array[Int], with an implicit conversion to ArrayOps occurring to perform the reverse operation. The value of seqReversed, on the other hand, will be computed by converting to ArraySeq first and invoking the variant of reverse that returns another ArraySeq.

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 Array by Martin Odersky for more information.

Companion
object
Source
Array.scala
trait Cloneable
class Object
trait Matchable
class Any

Value members

Concrete methods

def apply(i: Int): T

The element at given index.

Indices start at 0; xs.apply(0) is the first element of array xs. Note the indexing syntax xs(i) is a shorthand for xs.apply(i).

Value Params
i

the index

Returns

the element at the given index

Throws
ArrayIndexOutOfBoundsException

if i < 0 or length <= i

Source
Array.scala
override def clone(): Array[T]

Clone the Array.

Returns

A clone of the Array.

Definition Classes
Source
Array.scala
def length: Int

The length of the array

def update(i: Int, x: T): Unit

Update the element at given index.

Indices start at 0; xs.update(i, x) replaces the ith element in the array. Note the syntax xs(i) = x is a shorthand for xs.update(i, x).

Value Params
i

the index

x

the value to be written at index i

Throws
ArrayIndexOutOfBoundsException

if i < 0 or length <= i

Source
Array.scala