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 | stringis a closed, tagged union. Each stored value knows which alternative it holds.T?meansT | None.Nonehas no payload and never compares equal to a present value, so an absent value, an empty value and a filled value stay distinguishable: withint? count = None,count == 0isfalse.- 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?keepsNoneand converts a present value. Seelang.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 == Noneandx is Tnarrowx, and so does a type arm ofmatch. The narrowing applies in the branches ofifandelse, in the body of awhileloop and in the body and step of aforloop, in the arms of a conditional expressionc ? a : band ofmatch, 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, areadonlyorconstfield 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 (seelang.statements). Areadonlyfield 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 notreadonlyorconst, a top-level variable that some function assigns, a local that a=> exprfactory 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) SwhereSalways leaves (return,throw,breakorcontinue), the code that follows in the same block seescfalse: afterif (s == None) { return 0; }the value is astring. When anifhas anelseand one branch always leaves, the code after theifsees 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 || bis both sides false, soif (a == None || b == None) return;narrows bothaandbafter it.!negates what the test established: afterif (!(s == None))the value is a presentstring, and afterif (!(a != None && b != None)) return;both are present. x is Array<int>andx 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: withx : Array<int> | string, the test isx is Array<int>, andx is Array<string>is a compile error because it can never be true (lang.generics, Type tests). A class whose name only begins withArrayorMap, such asArrayList, is its own type and tests as that class.- Inside a class,
thisnarrows like a variable: inmatch (this) { Sub => this.subField }the arm readsSub'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: afters = "zz"astring?is astring. 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: insideif (n != None) { ... }, aftern += 1anint?is still anint, son *= 2andn < 9that follow are legal. A local declaration's initializer narrows the same way: afterstring? s = "a";the variable is astring, and afterstring? s = None;it isNone(wheres ?? d,s?.m()ands != Nonestill read it as its declaredstring?). An overload is still chosen by the declared type when one takes it exactly (seelang.argument-binding). A write in an operand that may not run (the right of??, an argument ofa?.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 amatchstarts from the narrowing that held before thematch, and a write in any arm ends that narrowing after thematch. 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. Aforstep runs after the body, so its assignments narrow nothing in the body, and a path the body assigns has no narrowing in the step. Acatchstarts with the narrowing that held before thetry, less every path thetrybody 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 everycatch, leaving out those that cannot complete (return,throw). Aftertry { s = None; f(); s = "y"; } catch (E e) { }astring?is astring?again; with acatchthat returns it is astring. A local declared in a nested scope (a block, aforinitializer, afor-invariable, acatchvariable) 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 andthisit captures (by value) only: not of a field,readonlyincluded, 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 == Noneandx != None, and aNonearm ofmatch, where the type ofxcannot holdNone(not a union withNone, 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 ?? byieldsawhen it is present andbotherwise. With a target, both sides are checked against it. Without one, its type is the merge (lang.merged-types) ofawithNoneremoved andb:Dog? ?? Animal()is anAnimal, ands ?? 5is a compile error whensis astring?.a?.m()anda?.bstop and giveNonewhenaisNone; the arguments are not evaluated. The result has typeR | None.- A value that may be
Noneis not an operand of string+. Withstring? s,s + "x","x" + s,None + "x","x" + Noneandt += sare compile errors ("no operator '+' between 'string' and 'string | None'"), and so is any other optional such as anint?. 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 += bis rejected wherevera + bis, so any union,int | decimalincluded, has no+=either. Withint? n,n + 1,1 + n,n += 1,n < 1,1 >= nand-nare compile errors ("no operator '+' between 'int | None' and 'int'", "no operator '-' on 'int | None'; narrow it first"), and so areNone + 1andNone < 1, including a local thatint? n = None;has narrowed toNone. Equality stays:n == 1andn != Noneare legal. Unwrap it first ((n ?? 0) + 1) or narrow it: on a narrowedn,n += 1works on theintand leavesnnarrowed, 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.