Skip to content

Collections

Kelvra currently ships built-in arrays, sets, and dictionaries. The tests under tests/ are the best source of truth for current behavior.

Array literals use square brackets.

var values Array<i32> = [1, 2, 3]
print(values[0])
values[1] = 9
values[0] += 4
values.push(7)
print(values.pop())
print(values.size())
print(values.has(3))

Array methods are push, pop, insert, remove, clear, size, isEmpty, first, last, and has. Indexed reads, indexed writes, and compound assignment on indexed elements are also supported.

Sets support constructor-style creation and membership operations.

var ids Set<i32> = Set(1, 2, 2, 3)
print(ids.size())
print(ids.has(2))
print(ids.add(4))
print(ids.remove(3))
var more Set<i32> = Set(3, 4, 5)
print(ids.union(more))
print(ids.intersect(more))
print(ids.difference(more))

Set methods are add, remove, has, clear, isEmpty, size, toArray, union, intersect, and difference. Set values can be iterated directly:

for (var item i32 : ids) {
print(item)
}

Dictionaries use key/value literals with braces.

var scores Dict<str, i32> = {"alice": 7, "bob": 9}
print(scores["alice"])
scores["alice"] = 8
print(scores.get("alice"))
scores.set("carol", 10)
print(scores.has("carol"))
print(scores.size())
print(scores.remove("carol"))

Dictionary methods are get, getOr, set, has, remove, clear, isEmpty, size, keys, and values. Bracket access reads and writes values. Direct foreach over a dictionary is rejected today; iterate a projection such as .keys() instead.

Collections are parameterized with angle-bracket type arguments:

var nums Array<i32> = []
var seen Set<str> = Set()
var players Dict<usize, i32> = Dict()

The codebase also uses nested collection types such as Dict<Array<i32>, i32>.

Local inference works well when the target type is already clear:

var nums Array<i32> = [1, 2, 3]
var empty Set<str> = Set()
var mapping Dict<str, i32> = {}

When the literal alone is ambiguous, keep the explicit collection type.

var nums Array<i32> = [1, 2, 3]
for (var n i32 : nums) {
print(n)
}
var scores Dict<str, i32> = {"alice": 7, "bob": 9}
for (var name str : scores.keys()) {
print(scores[name])
}