Collections
- Type[] is an ordered array and Type{} is a string-keyed map.
- Normal index access returns an optional value because a position or key may be missing.
- Collection methods have fixed receiver-specific contracts and typed it bindings.
Array And Map Types
1Expense[] expenses = []2number{} balances = {}3number[][] monthly_shares = []4Expense{} expenses_by_id = {}Type[]stores ordered values of one element type.Type{}stores values of one type under string keys.- Modifiers can nest, as in
number[][]orExpense{}[]. - An empty literal needs an explicit collection type because it has no member to infer from.
Index Results
1Expense? first = expenses[0]2number? alex_balance = balances["alex"]34with expenses[0] as expense {5 selected = expense6}Normal indexing is optional because an array position or map key may not exist. Prove presence with with, use ?? for a scalar fallback, or attach a declaration-level container fallback in full/backend Nenu.
Array Selection And Projection
1large = expenses.filter(it.amount >= 100)2first_open = expenses.first(it.status != ExpenseStatus.Settled)3last_open = expenses.last(it.status != ExpenseStatus.Settled)4titles = expenses.collect(it.title)5has_large = expenses.any(it.amount >= 100)6all_positive = expenses.all(it.amount > 0)| Method | Result |
|---|---|
filter(predicate) | All matching elements as T[]. |
first(predicate) | The first match as T?. |
last(predicate) | The last match as T?. |
collect(expression) | Projected values as U[]. |
any(predicate) | bool: at least one match. |
all(predicate) | bool: every element matches. |
Changing Arrays
1expenses.push(new_expense)2expenses = expenses + [new_expense]3expenses = expenses + imported_expensespush mutates an array and returns no value, so use it as its own statement. Array + returns a new array and requires the same element type on both sides.
Map Methods
1member_ids = balances.keys()2amounts = balances.values()3non_zero = balances.filterValues(it != 0)4public_balances = balances.filterKeys(it != "private")56number total = 07loop balances as member_id, amount {8 total = total + amount9}filterKeys binds it to a string key. filterValues binds it to the map value type. Iterate a map directly with two bindings; loop balances.entries() as key, value is equivalent supported sugar.
Common Mistakes
| Wrong | Correct | Reason |
|---|---|---|
expenses = [] as a first binding | Expense[] expenses = [] | Empty literals cannot infer an element type. |
expenses.push new_expense | expenses.push(new_expense) | Method calls require parentheses. |
Use push as a value | Use it as a statement. | Push returns no value. |
Treat expenses[0] as required | Use Expense? or a presence guard. | The index may be missing. |
