Optionals

Declaration

tape
let maybe: ?i64 = null;
let found: ?i64 = 42;

?T means “either a value of type T, or null.”

Null checking

tape
if (maybe != null) {
    io.print_i64(maybe!);
}

Unwrap

tape
let val: i64 = maybe!;  // traps if null

The ! operator unwraps the optional. If it’s null at runtime, the program traps.

Default values with or

tape
let val: i64 = maybe or { 0 };

The or { } block provides a fallback value when the optional is null.

As function returns

tape
fn find(items: []i64, target: i64) -> ?i64 {
    for (i in 0..items.len) {
        if (items[i] == target) { return i; }
    }
    return null;
}

let idx: ?i64 = find(data, 42);
if (idx != null) {
    io.println("found at index:");
    io.print_i64(idx!);
}

Difference from error returns

  • ?T — value might be absent (no error info, just “nothing”)
  • T or E — operation can fail with a specific error value

Use ?T for lookups and optional fields. Use T or E for operations that can fail with diagnostic information.

Last modified: