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

Null safety

The compiler enforces null safety: nullable values cannot be accessed without an explicit null check.
A check for value != null is required before:
When a variable has no explicit type, its type is inferred from the initial assignment and does not change. Therefore, a variable must be declared explicitly as nullable when required:
Similarly, when the initial value is null, its type must be specified:

Smart casts

After a null check, the compiler automatically narrows the type. This feature is known as “smart casts”. It exists in TypeScript and Kotlin, and makes working with nullable types more natural. Examples:
Smart casts apply to local variables, structure fields, and tensor/tuple indices.
Smart casts also work for initial values. Even if a variable declared as int? but initialized with a number, it’s a safe non-null integer:
When a variable is definitely null, its type becomes null, meaning it can be safely passed to any nullable type:

Operator ! (non-null assertion)

The ! operator in Tolk is similar to ! in TypeScript and !! in Kotlin. It allows bypassing the compiler’s check:
Sometimes “a developer knows better than the compiler”. For example:
Unlike local variables, global variables cannot be smart-cast. The ! operator is the only way to drop nullability from globals:
Therefore, ! is useful when non-nullability is guaranteed by conditions outside the code itself.

Stack layout and serialization

Atomics like int? or cell? / etc. are backed by either TVM NULL or a value. Non-atomics are tagged unions. Serialized as: null -> ‘0’, otherwise -> ‘1’+T, but address? is serialized specially. For details, follow TVM representation and Serialization.