Skip to main content
Tolk supports nullable types T?: they can hold a null value and are a shorthand for T | null. Any type can be made nullable: primitive types, structures, and other composites. The special null value cannot be assigned to a non-nullable type.

Null safety

The compiler enforces null safety: nullable values cannot be accessed without an explicit check.
When a variable has no explicit type, its type is inferred from the initial assignment. Nullable variables must be declared explicitly:
When the initial value is null, the type must be specified:

Smart casts

The nullable type is narrowed after the null check. This feature, known as smart casts, is available in many general-purpose languages.
Smart casts apply to local variables, structure fields, and tensor or tuple indices.
Smart casts also apply to initial values. Even if a variable is declared as int? but initialized with a number, it remains a safe non-null integer until it is reassigned:

Null-coalescing operator ??

The ?? operator returns the left operand if it is not null; otherwise it evaluates and returns the right operand. It is similar to ?? in TypeScript:
The operator has right associativity, which allows chaining:

Non-null assertion operator !

The ! operator bypasses the compiler’s nullability check. It is similar to ! in TypeScript and !! in Kotlin.
In some cases, the developer has knowledge that the compiler lacks:

Global variables

Unlike local variables, global variables cannot be smart-cast. The ! operator is the only way to narrow their type:
The ! operator is useful when conditions outside the code itself guarantee non-nullability.

Stack layout and serialization

Primitives like int or cell, when nullable, are serialized as a TVM value or null. Nullable structures and other composites are represented as tagged unions:
  • if their type is null, they are serialized as 0;
  • otherwise, they are serialized as 1 followed by the non-null value.
The address? type is an exception, and it is serialized in a different way.