Sub topic 3
What "sound" means and what the compiler guarantees
This chapter assumes you can read basic Dart, know the difference between String and String?, and can run a file with dart run or in DartPad. The goal is to understand exactly what Dart promises about null, where that promise comes from, and where it deliberately stops.
What soundness means
A type system is sound when the static type of an expression always matches the value it produces at runtime. Dart's null safety applies this to null:
- If an expression has a non-nullable static type such as
String, it can never evaluate tonullat runtime. - If an expression has a nullable type such as
String?, it may benull, and the compiler stops you from using it as if it were not.
The first rule is the guarantee. The second rule is how the compiler enforces it.
In Dart, T? is the union of T and the type Null. The only value of type Null is null. The type Null is a subtype of every nullable type and of no non-nullable type. That is why this fails:
void main() {
String name = 'Ada';
String? nickname;
// name = null; // Error: 'Null' is not a subtype of 'String'
// print(nickname.length); // Error: 'length' can't be accessed on 'String?'
print(name.length); // 3
print(nickname?.length); // null
}The two commented lines never reach a running program. Both are rejected before the program starts.
Why soundness matters
Soundness is a stronger promise than "the analyzer warns about most null mistakes". Because the promise holds everywhere, the compiler can rely on it.
- Developers can trust a signature. A function that takes
Stringdoes not need to check for null, because callers cannot pass it. - The compiler can drop null checks. When a value is known to be non-null, generated code does not need to test it before use. Your code can be smaller and faster as a result.
- Refactoring is safer. If you change a return type from
StringtoString?, every caller that depends on a non-null result fails to compile and points you to the fix.
Compare this with an unsound check, such as a linter that flags likely null misuse. A linter can miss cases. A sound type system cannot miss one, within the rules described below.
How the guarantee is enforced
Static checking alone is not enough. Some values enter a program in ways the compiler cannot see through, so Dart combines compile-time checks with runtime checks at the boundaries.
Compile-time checks
The type checker enforces these rules:
- You cannot assign
nullor aT?value to aTvariable, parameter, or return value. - You cannot call a method or read a property on a
T?value, except the members thatObjectdefines for null, such astoString(),hashCode, and==. - A non-nullable variable must be definitely assigned before use. A non-nullable field must be initialized by the end of the constructor's initializer phase.
- A function with a non-nullable return type must return a value on every path.
Runtime checks
Some types are only known at runtime. Dart inserts a check at the point where a value crosses into a more precise type. If the value is null and the target type is non-nullable, the check throws immediately.
The first boundary is dynamic. A dynamic value can hold anything, including null, and assigning it to a typed variable adds an implicit cast.
void main() {
dynamic raw = null;
try {
String s = raw; // implicit downcast from dynamic: checked at runtime
print(s.length); // never reached
} on TypeError {
print('caught at the boundary, not later');
}
}The error occurs on the assignment, not on the later use of s. That matters for debugging: the failure points to where the bad value entered, not to a distant line where it happened to be used.
The second boundary is generic variance. In Dart, List<int> is a subtype of List<int?>, because every int is also an int?. Reading through the wider type is safe. Writing through it is not, so Dart checks writes at runtime.
void main() {
List<int> ints = [1, 2];
List<int?> view = ints; // allowed: List<int> is a List<int?>
print(view.length); // 2
try {
view.add(null); // the real list only accepts int
} on TypeError {
print('add(null) rejected');
}
print(ints); // [1, 2]
}The list remains a List<int> no matter which variable refers to it. The runtime check keeps null out of it.
What the guarantee does not cover
Soundness says a non-nullable expression never holds null. It does not say your program cannot throw. Several features let you move a null problem from compile time to runtime on purpose, and each is a place where you take responsibility.
| Feature | What you promise | What happens if you are wrong |
|---|---|---|
| `x!` | "This is not null here." | Throws at the `!` expression |
| `x as T` | "This value is a `T`." | Throws a `TypeError` at the cast |
| `late` | "This is assigned before it is read." | Throws `LateInitializationError` on read |
| `dynamic` | "I will handle the types myself." | A runtime check throws when the value is used as a typed value |
In every row, the error appears at the point of the broken promise. The non-nullable variable still never holds null. Here is the late case:
late String config;
void main() {
try {
print(config.length);
} on LateInitializationError {
print('config was read before it was assigned');
}
config = 'prod';
print(config.length); // 4
}The variable config is declared String, and reading it never yields null. Reading it too early throws instead. This is why the guarantee still holds: the program stops rather than letting a null masquerade as a String.
Here is the null assertion:
String? find(List<String> items, String key) {
for (final item in items) {
if (item == key) return item;
}
return null;
}
void main() {
print(find(['a', 'b'], 'a')!.length); // 1
try {
print(find(['a', 'b'], 'z')!.length);
} on Error {
print('null check operator failed');
}
}Soundness also does not cover other kinds of runtime failure. A RangeError from a bad list index, a StateError from calling first on an empty list, and a FormatException from int.parse are all unrelated to null types.
Soundness across a whole program
The guarantee holds for a program when every library in it uses null safety. A library that can still produce null for a non-nullable type would break the promise for everything that calls it.
Before Dart 3, the language supported mixed-version programs. Older code ran in an unsound mode where the guarantee was off, and sound null safety turned on only when all libraries opted in. Dart 3 removed that mode. It requires null safety, so every program built with Dart 3 is sound with respect to null.
Reading the guarantee as a design tool
You can use soundness to decide how to write types.
- Make a type non-nullable when absence is not a valid state. A
Useralways has aname, soString nameis correct. The compiler now enforces this at every construction site. - Make a type nullable when absence is a real, expected state, such as an optional email. The
?makes callers deal with it. - Avoid nullable types as a lazy default. Each
?adds a check for every caller, so it has a cost. - Prefer a check or a safe operator to
!. When you use!, you replace a compile-time proof with a runtime assumption.
The same reasoning applies to return types. A function returning String? tells callers "I may not find anything". A function returning String tells them "you always get a value". Because the guarantee is sound, callers can trust either signature without reading the function body.
Summary
- Sound null safety means a non-nullable static type never holds null at runtime.
T?isTorNull, and the compiler blocks unchecked use of it.- Static checks catch most errors. Runtime checks at
dynamicconversions, casts, and generic variance catch the rest. !,as,late, anddynamictrade a compile-time proof for a runtime promise, and each throws where the promise breaks.- Dart 3 requires null safety, so the guarantee applies to every program.
Exercise
Given List<int> nums = [1, 2, 3]; List<int?> wide = nums; wide.add(null);, does this code compile, and what happens when it runs? Explain which kind of check is involved.
Show answer
It compiles, because List<int> is a subtype of List<int?>, so the assignment is allowed. At runtime, wide.add(null) throws a TypeError. The object is still a List<int>, and Dart checks the argument of add at runtime because the static type alone cannot prove the write is safe. This runtime check keeps null out of a list that promises non-null elements.
Exercise
A function declares String label; as a top-level late variable and reads it before assigning it. Does this break the soundness guarantee for label? What is thrown, and why does the guarantee still hold?
Show answer
It does not break the guarantee. Reading an unassigned late variable throws LateInitializationError, so no null value is ever produced as a String. The program stops at the read instead of continuing with a bad value. The cost is that the mistake shows up at runtime rather than compile time.