Skip to content

34 Flow narrowing ​

A null check can prove a nullable value non-null inside a branch.

norm
Void show(String? value) {
  if value == null {
    printLine("none")
  } else {
    printLine(value.codePointSize())
  }
}

main() {
  show(value: null)
  show(value: "Norm")
}

Expected output:

text
none
4

In the else branch, value cannot be null, so codePointSize() is a valid String call. Outside the branch, that proof may no longer hold if the value can change.

Try it: Reverse the condition and move the size call into the non-null branch.

Precise rules: Reference.

Norm 0.25