Proposal
Add two new operators for ergonomic null handling in DataSonnet expressions:
?? — Null Coalescing
payload.currency ?? "USD"
Returns the left-hand side if it is not null, otherwise evaluates and returns the right-hand side. Unlike default (which catches any error via try/catch), ?? specifically checks for null values only. The right-hand side is lazily evaluated (short-circuit).
?. / ?[ — Optional Chaining
payload.order?.customer?.email
payload.items?[0]
Safely accesses fields or indices on a value that may be null. If the value is null, returns null instead of throwing an error. Chainable and combinable with ??:
payload.address?.city ?? "Unknown"
Difference from default
|
default |
?? |
| Missing field |
catches error, returns fallback |
throws (field not found) |
| Null value |
catches error (if any), returns fallback |
returns fallback |
| Other error |
catches, returns fallback |
throws |
| Semantics |
try/catch |
null check |
Precedence
?? has the lowest precedence of all binary operators (lower than ||), matching JavaScript/Kotlin semantics. x ?? 1 + 2 parses as x ?? (1 + 2).
Implementation
A working implementation is available at gnodet/datasonnet-mapper@null-coalescing-optional-chaining with:
- Parser, AST, and evaluator changes (4 files modified)
- 34 tests covering null coalescing, optional chaining, edge cases, precedence, error semantics, and combined usage
- Documentation in
language.adoc
Happy to open a PR if the project accepts external contributions.
Proposal
Add two new operators for ergonomic null handling in DataSonnet expressions:
??— Null CoalescingReturns the left-hand side if it is not
null, otherwise evaluates and returns the right-hand side. Unlikedefault(which catches any error via try/catch),??specifically checks for null values only. The right-hand side is lazily evaluated (short-circuit).?./?[— Optional ChainingSafely accesses fields or indices on a value that may be
null. If the value is null, returnsnullinstead of throwing an error. Chainable and combinable with??:Difference from
defaultdefault??Precedence
??has the lowest precedence of all binary operators (lower than||), matching JavaScript/Kotlin semantics.x ?? 1 + 2parses asx ?? (1 + 2).Implementation
A working implementation is available at
gnodet/datasonnet-mapper@null-coalescing-optional-chainingwith:language.adocHappy to open a PR if the project accepts external contributions.