Expressions
Indexing
The square-bracket operator reads and writes elements through an indexer accessor, and rebinds the variable when the target is an array.
since 0.1.0-alpha.1linuxwindowswasm
Description
a[i] reads an element and a[i] = v writes one. On a class, they call the indexer accessors declared with the selector ([]):
get ([])(int i) => cells[i]; // read: a[i]
set ([])(int i, int v) cells[i] = v; // write: a[i] = v (the value parameter is last)
On a mutable object the set accessor changes the object in place. On an array, which is a value, a[i] = v is shorthand for rebinding a to a new array whose slot i holds v; any other variable that held the old array is unaffected.
An indexer on a class, and arrays as values
class Grid {
Array<int> cells = [0, 0, 0, 0];
get ([])(int i) => cells[i];
set ([])(int i, int v) cells[i] = v * 10;
}
void main() {
Grid g = Grid();
g[1] = 4;
console.writeln(g[1]);
console.writeln(g[0]);
Array<int> a = [1, 2, 3];
Array<int> b = a;
a[0] = 99;
console.writeln(a);
console.writeln(b);
Map<string, int> m = Map();
m["x"] = 1;
console.writeln(m["x"]);
}
main();
40
0
[99, 2, 3]
[1, 2, 3]
1
Rules
a[i]calls the([])get accessor ofa's class, anda[i] = vcalls its([])set accessor.- On a mutable object the set accessor mutates the object in place.
- On an array,
a[i] = vrebindsa; a copy of the array taken earlier keeps its old contents. - An index outside the array throws a
RuntimeException. Reading a missing key with a map'satmethod throws as well.
Examples
An out-of-range index is a catchable exception
Array<int> xs = [1, 2, 3];
try {
console.writeln(xs[5]);
} catch (RuntimeException e) {
console.writeln("caught: ${e.message}");
}
caught: index 5 out of bounds (length 3)