Skip to content

Instantly share code, notes, and snippets.

@lrhn
Last active September 16, 2020 09:27
Show Gist options
  • Save lrhn/5a783a27daed945ead642728a80229c6 to your computer and use it in GitHub Desktop.
Save lrhn/5a783a27daed945ead642728a80229c6 to your computer and use it in GitHub Desktop.
Dart Null Safety Promotion
main([args]) {
String? x = args == null ? 'foo' : null;
{
String? y = x;
ignore(y!); // Promotes along non-throwing branch;
print(y.length);
}
{
String? y = x;
ignore(y as String); // Promotes along non-throwing branch;
print(y.length);
}
{
String? y = x;
// Promotes along true branch.
if (y != null) print(y.length);
}
{
String? y = x;
// Promotes along false branch.
if (y == null) {
} else {
print(y.length);
}
}
{
String? y = x;
// Promotes along true branch.
if (y is String) print(y.length);
}
{
String? y = x;
// Promotes along true branch, but recommends `y != null`.
if (y is! Null) print(y.length);
}
// DOES NOT PROMOTE
{
String? y = x;
// Does not promote even though y is String? && y is Object => y is String
if (y is Object) print(y.length);
// Does not promote even though `identical(y, null)` => `y == null`
if (!identical(y, null)) print(y.length);
if (identical(y, null)) {
} else {
print(y.length);
}
// Does not promote even though `y == null` => `y?.length == null`
ignore((y?.length)!);
print(y.length);
// Does not promote even though `y == "foo"` => `y != null`.
if (y == "foo") print(y.length);
}
}
void ignore(_) {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment