Skip to content

Instantly share code, notes, and snippets.

@EliteMasterEric
Created June 23, 2025 19:39
Show Gist options
  • Select an option

  • Save EliteMasterEric/2a025600e9d5ec9cf4fd7cc6c0a3c0af to your computer and use it in GitHub Desktop.

Select an option

Save EliteMasterEric/2a025600e9d5ec9cf4fd7cc6c0a3c0af to your computer and use it in GitHub Desktop.
Examples of the different types of null safety.
class MyClass {
public var foo:Null<String>;
public function cleanup() {
foo = null;
}
}
class Test {
public static function main():Void {}
// Loose assumes that nullable values are non-nullable, even if the value could be modified after the check.
@:nullSafety(Loose)
function testLooseValid(input:MyClass) {
if (input.foo != null) {
// This compiles fine, since we just checked if the value is null.
trace(input.foo.length);
trace(input.foo.length);
input.cleanup();
// This will compile but will throw a Null Object Reference.
trace(input.foo.length);
}
}
// Loose assumes that nullable values are non-nullable, even if the value could be modified after the check.
@:nullSafety(Strict)
function testStrictInvalid(input:MyClass) {
if (input.foo != null) {
// This compiles fine, since we just checked if the value is null.
trace(input.foo.length);
trace(input.foo.charAt(0));
input.cleanup();
// This will not compile, since there was non-sequential access to the field.
// cleanup() may have changed the field value.
trace(input.foo.length);
}
}
// Loose assumes that nullable values are non-nullable, even if the value could be modified after the check.
@:nullSafety(Strict)
function testStrictThreadedInvalid(input:MyClass) {
if (input.foo != null) {
// This does not compile, because in a multi-threaded environment, another thread may have called cleanup()
trace(input.foo.length);
}
}
// Loose assumes that nullable values are non-nullable, even if the value could be modified after the check.
@:nullSafety(Strict)
function testStrictValid(input:MyClass) {
var localFoo:Null<String> = input.foo;
if (localFoo != null) {
// This compiles fine, since you can't change localFoo from another thread.
trace(localFoo.length);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment