8.12

2.2 Arrays🔗ℹ

The Array constructor is similar to List, but it creates an array, which has a fixed length at the time that it’s created and offers constant-time access to any element of the array. Like a list, an array is indexable. Unlike a list, an array is mutable, so [] for indexing can be combined with := for assignment.

def buckets = Array(1, 2, 3, 4)

> buckets[0]

1

> buckets[1] := 5

> buckets

Array(1, 5, 3, 4)

Array is also an annotation and a binding contructor, analogous to List, and Array.now_of and Array.later_of are annotation constructors. The Array binding form does not support ... or &, but the Array constructor supports ... and &.

The MutableList constructor and annotation corresponds to an object that contains a list, where the object can be mutated to change the list that it contains. Like an array, a mutable list supports indexing and update via [] and :=. Unlike an array, a mutable list supports operations that add or remove elements.

def items = MutableList(1, 2, 3, 4)

> items[0]

1

> items[1] := 5

> items

MutableList[1, 5, 3, 4]

> items.insert(2, 2.5)

> items

MutableList[1, 5, 2.5, 3, 4]

> items.append([10, 20, 30])

> items

MutableList[1, 5, 2.5, 3, 4, 10, 20, 30]