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.null, the type must be specified:
Smart casts
The nullable type is narrowed after thenull check. This feature, known as smart casts, is available in many general-purpose languages.
int? but initialized with a number, it remains a safe non-null integer until it is reassigned:
Non-null assertion operator !
The ! operator bypasses the compiler’s nullability check. It is similar to ! in TypeScript and !! in Kotlin.
Global variables
Unlike local variables, global variables cannot be smart-cast. The! operator is the only way to narrow their type:
! operator is useful when conditions outside the code itself guarantee non-nullability.
Stack layout and serialization
Primitives likeint 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 as0; - otherwise, they are serialized as
1followed by the non-null value.
address? type is an exception, and it is serialized in a different way.