LEVIATHAN vd52e79c4 · d52e79c486

Types

Unions and optionals

Closed unions T | U, the optional T?, narrowing with != None and is, and the ?? and ?. operators.

since 0.1.0-alpha.1linuxwindowswasm

Description

A union type int | string holds a value of exactly one of the listed types. A value of type T can be assigned to any union that contains T.

T? is shorthand for T | None. None is the type of the single value that means "absent". There is no null. An optional field starts as None, and a general union starts with the default value of its first member.

You cannot call a method or read a member through a union until the compiler knows which alternative you hold. Test the value, and inside the tested branch the type is narrowed:

Narrowing an optional and a union

use io::console;

string describe(int | string v) {
    if (v is int) {
        return "int ${v + 1}";
    } else {
        return "string ${v.toUpper()}";
    }
}

int lengthOf(string? s) {
    if (s != None && s.length() > 0) {
        return s.length();
    }
    return 0;
}

console.writeln(describe(41));
console.writeln(describe("hi"));
console.writeln(lengthOf("abc"));
console.writeln(lengthOf(None));
int 42
string HI
3
0

Rules

The types.

  • int | string is a closed, tagged union. Each stored value knows which alternative it holds.
  • T? means T | None. None has no payload and never compares equal to a present value, so an absent value, an empty value and a filled value stay distinguishable: with int? count = None, count == 0 is false.
  • A field of an optional type defaults to None. A union field or variable of another kind defaults to the default of its first member.
  • A numeric optional such as float? keeps None and converts a present value. See lang.numeric-conversions.

Narrowing.

  • Calling a member of a union value, or reading one, is a compile error until it is narrowed: "narrow the union before calling members".
  • x != None, x == None and x is T narrow x, and so does a type arm of match. The narrowing applies in the branches of if and else, in the body of a while loop and in the body and step of a for loop, in the arms of a conditional expression c ? a : b and of match, on the right of && (s != None && s.length() > 0), and on the right of ||, which sees its left side false (s == None || s.length() == 0).
  • What narrows: a local variable, a parameter, a loop or catch variable, this, a readonly or const field reached through any of these (p.f, this.next.label), and a top-level or namespace variable (g, N::g) that no function, method or lambda in the program assigns (see lang.statements). A readonly field does not narrow inside a constructor of the class that declares it, which may still assign it, nor when some class declares a getter of that name on the declaring class or a class derived from it ("a getter of that name may intercept the read").
  • Nothing else narrows: a mutable field (o.f, this.f, a bare field name in a method), a weak field, a static field that is not readonly or const, a top-level variable that some function assigns, a local that a => expr factory visible at that point assigns, an element (a[i], m[k]). A call between the test and the use could change any of them. Using one as if it had been narrowed is a compile error that says why: "'o.f' cannot be narrowed: it is a mutable field; copy it into a local first", "'g' cannot be narrowed: it is a global assigned by function 'reset'; copy it into a local first", "'k' cannot be narrowed: it is a local assigned by a bind factory; copy it into a local first". Copy the value into a local, test the local and use it (example below).
  • An early exit narrows. After if (c) S where S always leaves (return, throw, break or continue), the code that follows in the same block sees c false: after if (s == None) { return 0; } the value is a string. When an if has an else and one branch always leaves, the code after the if sees the facts of the other branch. The facts end with the enclosing block. A call to a function that always throws is not an exit the compiler sees, so it does not narrow.
  • The false side of a || b is both sides false, so if (a == None || b == None) return; narrows both a and b after it. ! negates what the test established: after if (!(s == None)) the value is a present string, and after if (!(a != None && b != None)) return; both are present.
  • x is Array<int> and x is Map<string, int> test for the built-in collections. Like every generic class, they are written with the type arguments the subject's type fixes: with x : Array<int> | string, the test is x is Array<int>, and x is Array<string> is a compile error because it can never be true (lang.generics, Type tests). A class whose name only begins with Array or Map, such as ArrayList, is its own type and tests as that class.
  • Inside a class, this narrows like a variable: in match (this) { Sub => this.subField } the arm reads Sub's members.
  • What ends a narrowing: an assignment, plain or compound (x = v, x += v), to the narrowed path or to something it is reached through, under any spelling of the same variable (an alias, N::g). A plain assignment of a value of one of the declared types narrows the path to that type again: after s = "zz" a string? is a string. A compound assignment to a path that is narrowed to one of the declared types narrows it to the operation's result in the same way: inside if (n != None) { ... }, after n += 1 an int? is still an int, so n *= 2 and n < 9 that follow are legal. A local declaration's initializer narrows the same way: after string? s = "a"; the variable is a string, and after string? s = None; it is None (where s ?? d, s?.m() and s != None still read it as its declared string?). An overload is still chosen by the declared type when one takes it exactly (see lang.argument-binding). A write in an operand that may not run (the right of ??, an argument of a?.m(...)) ends the narrowing of that path and establishes none. A write on the right of && or || ends the left side's narrowing of that path, and so does a write in an assignment's right side for its target (the right side runs first). Each arm of a match starts from the narrowing that held before the match, and a write in any arm ends that narrowing after the match. A loop drops, before its body, the narrowing of every path its condition, step or body assigns, because a later pass sees the assigned value. A for step runs after the body, so its assignments narrow nothing in the body, and a path the body assigns has no narrowing in the step. A catch starts with the narrowing that held before the try, less every path the try body assigns, since it is entered from any point of the body; after the statement, a narrowing holds only if it holds at the end of the body and at the end of every catch, leaving out those that cannot complete (return, throw). After try { s = None; f(); s = "y"; } catch (E e) { } a string? is a string? again; with a catch that returns it is a string. A local declared in a nested scope (a block, a for initializer, a for-in variable, a catch variable) is a different variable from an outer one of the same name: it hides the outer narrowing while it is in scope, and at the end of the scope the outer narrowing is back, untouched by what happened to the local. A lambda body starts with the narrowing of the locals, parameters and this it captures (by value) only: not of a field, readonly included, and not of a top-level variable, which top-level code may assign before the lambda runs.
  • A test that can never be true is a compile error: x is None, x == None and x != None, and a None arm of match, where the type of x cannot hold None (not a union with None, not a type parameter): "'n' can never be None: its type 'int' is not optional", and for != "...; this test is always true".

Defaults and chaining.

  • a ?? b yields a when it is present and b otherwise. With a target, both sides are checked against it. Without one, its type is the merge (lang.merged-types) of a with None removed and b: Dog? ?? Animal() is an Animal, and s ?? 5 is a compile error when s is a string?.
  • a?.m() and a?.b stop and give None when a is None; the arguments are not evaluated. The result has type R | None.
  • A value that may be None is not an operand of string +. With string? s, s + "x", "x" + s, None + "x", "x" + None and t += s are compile errors ("no operator '+' between 'string' and 'string | None'"), and so is any other optional such as an int?. Unwrap it first ((s ?? "") + "x") or narrow it.
  • An optional has no arithmetic, no compound assignment and no ordering. A compound assignment follows the binary operator: a += b is rejected wherever a + b is, so any union, int | decimal included, has no += either. With int? n, n + 1, 1 + n, n += 1, n < 1, 1 >= n and -n are compile errors ("no operator '+' between 'int | None' and 'int'", "no operator '-' on 'int | None'; narrow it first"), and so are None + 1 and None < 1, including a local that int? n = None; has narrowed to None. Equality stays: n == 1 and n != None are legal. Unwrap it first ((n ?? 0) + 1) or narrow it: on a narrowed n, n += 1 works on the int and leaves n narrowed, so further operations work too.

Examples

Defaults and optional chaining:

?? and ?. on optional values

use io::console;

class Req {
    string? host;
    int | string id = 5;
}

Req r = Req();
console.writeln(r.host == None);
console.writeln(r.id is int);
string? name = None;
console.writeln(name ?? "anonymous");
r.host = "example.org";
console.writeln(r.host?.toUpper());
name = "ada";
console.writeln(name?.length());
string? nothing = None;
console.writeln(nothing?.length() == None);
true
true
anonymous
EXAMPLE.ORG
3
true

Narrowing a path in a loop:

Narrowing in a while loop

use io::console;

class Node {
    int value = 0;
    Node? next;
}

Node tail = Node();
tail.value = 3;
Node head = Node();
head.value = 1;
head.next = tail;
Node? cur = head;
int total = 0;
while (cur != None) {
    total += cur.value;
    cur = cur.next;
}
console.writeln(total);
4

Narrowing after an early exit, and with ||:

Early exit and ||

use io::console;

string join(string? a, string? b) {
    if (a == None || b == None) return "missing";
    return a + "-" + b;
}

bool blank(string? s) {
    return s == None || s.length() == 0;
}

console.writeln(join("x", "y"));
console.writeln(join("x", None));
console.writeln(blank(""));
console.writeln(blank("z"));
x-y
missing
true
false

A mutable field is copied into a local before it is tested; the local narrows, and a call cannot change it:

Binding a field to a local

use io::console;

class Cache {
    string? value = "cached";
    void clear() { value = None; }
    int size() {
        string? v = this.value;
        if (v == None) return 0;
        clear();
        return v.length();
    }
}

Cache c = Cache();
console.writeln(c.size());
console.writeln(c.size());
6
0

Arithmetic and ordering on an optional, after unwrapping or narrowing:

Arithmetic on an optional

use io::console;

int next(int? n) {
    if (n == None) return 0;
    n += 1;
    n *= 2;
    return n;
}

int? count = None;
count = (count ?? 0) + 1;
console.writeln(count ?? -1);
console.writeln(next(None));
console.writeln(next(41));
int? limit = None;
console.writeln((limit ?? 10) < 5);
int? delta = 3;
if (delta != None) console.writeln(-delta);
1
0
84
false
-3

Notes

?? and ?. work on an optional without narrowing it first.

See also

  • Type expressions — How a type is written: names, qualified names, generic instantiations, unions, optionals and function types.