Last active
June 9, 2020 16:42
-
-
Save RedBrogdon/5a80bfd8e835bb470f56fcc381f901ed to your computer and use it in GitHub Desktop.
Snippet 5: Conditional access
This file contains 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
// Conditional access is a handy way to | |
// tighten up code that needs to read | |
// properties that could be null: | |
// | |
// a?.b | |
// | |
// The expression above evaluates to the | |
// value of `b` as long as `a` isn’t | |
// null. If `a` is null, then the expression | |
// evaluates to null. Try using conditional | |
// access to fix this code. | |
class BigThing { | |
LittleThing little = LittleThing(); | |
} | |
class LittleThing { | |
int fetchInt() => 12; | |
} | |
void main() { | |
final BigThing? big = BigThing(); | |
print('The value is:'); | |
print(big.little.fetchInt()); | |
} | |
// Without null safety, *two* conditional | |
// access operators are needed for this | |
// code to work (one after `big` and one | |
// after `little`). With null safety, | |
// conditional access can short-circuit, | |
// so this expression only requires a | |
// single `?`. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment