Try it in the playground

Arrays and maps

An array<T> grows with append, has a size, and supports iteration. A Map<K, V> associates keys with values; get returns a nullable value because the key might not exist. Explicit type arguments keep an empty map's intended key and value types clear. When a missing key means there is nothing more to do, bind it with val count = counts.get(key) ?? return in a function that returns void. Use ?? 0 when zero is the right fallback.

The example uses integer values so iteration and map storage copy those values. Resources and borrowed views have additional ownership rules; do not assume that copying an integer and transferring a resource are the same operation. If an array can be empty, use the checked first-element idiom.

Use for (n in numbers) to read the values directly. When you also need the position, iterate over 0 until numbers.size and bind numbers[i] inside the loop. The range stops before numbers.size, so the last index is one less than the size.

See arrays, maps, and array operations.

Runnable source:

import "abla/io"

fun main {
    val numbers = [2, 3]
    numbers.append(5)
    var sum = 0
    for (n in numbers) sum += n
    val counts: Map<string, int> = Map()
    counts.set("sum", sum)
    println("${numbers.size} items, sum ${counts.get("sum") ?? 0}")
    println("absent ${counts.get("absent") ?? -1}")
    for (i in 0 until numbers.size) {
        val n = numbers[i]
        println("[$i] $n")
    }
}
// output:
// 3 items, sum 10
// absent -1
// [0] 2
// [1] 3
// [2] 5

Previous · Tour · Next

Built from compiler source ba5d6b7d. Examples and generated signatures follow that source revision.