nenu-lang / defaults-and-fallbacks
StableDefaults And Fallbacks
- A default block supplies fields for one named type or enum variant.
- A container fallback belongs to one array or map declaration and changes missing-index results from optional to required.
- Default blocks and collection fallbacks solve different problems and use different syntax.
Defaults For Named Types
code
1type ExpenseDraft {2 title: string3 amount: number4 note: string?5}67default ExpenseDraft {8 title: "Untitled expense"9 amount: 010}A default target must exist, each field must exist on that target, and every default value must match its field type. Only one default block may target the same named type.
Defaults For Enum Variants
code
1enum ExpenseStatus {2 Draft,3 Open,4 Submitted,5 Approved { approved_at: time },6 Rejected { reason: string },7 Settled8}910default ExpenseStatus.Rejected {11 reason: "No reason supplied"12}Target the structured variant with Enum.Variant. A unit variant has no fields to default.
Container Fallbacks
code
1type BalanceLabel {2 label: string3 amount: number4}56BalanceLabel { label: "Unknown", amount: 0 } [] rows = []7BalanceLabel first = rows[0]89BalanceLabel { label: "Unknown", amount: 0 } {} by_member = {}10BalanceLabel missing = by_member["missing"]The fallback value appears before the collection marker. Missing array positions and map keys return that value, so the result is not optional.
Fallback Ownership Rules
- The fallback must satisfy the named element type.
- It is evaluated once when the declaration runs.
- It belongs only to that declaration.
- Assigning the collection to a normal array or map does not copy fallback behavior.
- Normal collections without a fallback keep optional index results.
- An empty object fallback must be spaced:
BalanceLabel {} []. CompactBalanceLabel{}[]means an array of maps.
Choose The Right Mechanism
| Need | Use |
|---|---|
| Fill omitted fields on a named value | default Type { ... } |
| Fill fields on a structured enum variant | default Enum.Variant { ... } |
| Replace one absent scalar expression | optional ?? fallback |
| Handle present or absent branches | with or without |
| Replace a missing array index or map key | A declaration-level container fallback. |
| Represent no elements | An empty array or map. |
Common Mistakes
| Mistake | Correction |
|---|---|
| Use a default when absence is meaningful | Keep the value optional. |
| Assume a fallback persists data | Use an entity default and explicit save when persistence is intended. |
| Use container fallbacks in Page Script | Initialize browser state explicitly. |
| Define two defaults for the same target | Keep one unambiguous default block. |
