Last active
September 16, 2020 09:27
-
-
Save lrhn/5a783a27daed945ead642728a80229c6 to your computer and use it in GitHub Desktop.
Dart Null Safety Promotion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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