Optionals And Absence
- Type? means one primitive or named scalar may be absent.
- The only absent value is ?; Nenu has no null, undefined, nil, or none.
- Use ?? for one expression fallback and presence guards for multi-statement control flow.
Declaring An Optional
1string? note2time? settled_at = ?3Expense? selected_expense4User? selected_memberThe question mark belongs to the type. An optional declaration may omit its right side, which starts it absent. Assign ? later to clear an optional value.
Coalescing One Expression
1string? draft_note = ?2number? draft_amount = ?34string label = draft_note ?? "No note"5number display_amount = draft_amount ?? 0left ?? fallback returns the present left value or the fallback. The fallback must match the unwrapped left type. Coalescing does not make the original optional present afterward.
Optional Containers Are Invalid
| Invalid | Use instead | Why |
|---|---|---|
Expense[]? | Expense[] expenses = [] | An empty array represents no elements. |
number{}? | number{} balances = {} | An empty map represents no entries. |
User?[] | A non-optional element type or another explicit model. | Optional elements inside containers are rejected. |
{ amount: number }? | Put optional markers on individual fields. | Structural shapes themselves are not optional. |
Reading Requires Proof
1string note = expense.noteA required destination cannot receive an optional value directly. Choose a fallback when one expression is enough, or use a presence guard when later statements depend on the value being present.
Common Mistakes
| Wrong | Correct |
|---|---|
string note = null | string? note = ? |
note? as a runtime test | with note { ... } |
if note { ... } | with note as text { ... } |
Expense[]? | Expense[] expenses = [] |
