Nullable Types
By default, every value in Cloth is non-null. The compiler enforces this: a non-nullable variable can never hold null. A type opts in to nullability with the ! suffix.
The ! suffix
The postfix ! on a type expression marks that type as nullable. A nullable type may hold a regular value of its underlying type, or it may hold null.
let name: string = "Cloth"; // never null
let title: string! = null; // nullableThe suffix is part of the type expression. Wherever a type can be written — in fields, parameters, return types, and casts — ! may follow it.
The null literal
The keyword null is the literal for the absent value. It has no type of its own; instead, it is assignable to any nullable type. Assigning null to a non-nullable type is a compile-time error.
Nullable fields and accessors
A field declared with a nullable type may be assigned null. The unfinished cloth.lang.error.Error class shows a typical pattern, where a nullable string is exposed through a public getter:
public class (string! message) {
public const string! message { public getter; };
}Here message may legitimately be absent, and callers must account for that possibility.
The fallback operator
The ?? operator (also called the fallback operator) supplies a value when its left operand is null. The expression a ?? b evaluates to a if a is non-null and to b otherwise. The result type is non-nullable when b is non-nullable.
Interaction with maybe clauses
A function may declare a maybe clause listing the error types it can produce. A maybe clause is independent of the return type’s nullability — the two describe different concerns:
- The return type describes the shape of a successful value, including whether it can be
null. - The
maybeclause describes what error types the function can throw.
See Memory and Errors for the full rules around maybe.
Summary
| Form | Meaning |
|---|---|
T | Non-nullable. Always holds a valid value. |
T! | Nullable. May hold a value or null. |
null | The absent-value literal. Assignable to any nullable type. |
a ?? b | Fallback. Returns b if a is null. |
Nullability is enforced statically. The compiler refuses programs that could observe null through a non-nullable type.