Last active
July 21, 2020 00:45
-
-
Save RedBrogdon/88970173429a487e82caf8ccf949157e to your computer and use it in GitHub Desktop.
Snippet 11: Late and lazy
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
// Here's another pattern that `late` can | |
// help with: lazy initialization for | |
// expensive non-nullable fields. | |
// | |
// Try running this code without changing | |
// it. What do you think will change if | |
// you make `_cache` a `late` field? | |
int _computeValue() { | |
print('Computing value...'); | |
return 3; | |
} | |
class CachedValueProvider { | |
final _cache = _computeValue(); | |
int get value => _cache; | |
} | |
void main() { | |
print('Calling constructor...'); | |
var provider = CachedValueProvider(); | |
print('Getting value...'); | |
print('The value is ${provider.value}!'); | |
} | |
// Fun fact: once you add `late` to the | |
// declaration of `_cache`, you can move | |
// the `_computeValue` function into the | |
// `CachedValueProvider` class and the | |
// code will still work! Initialization | |
// expressions for `late` fields can use | |
// instance methods in their initializers. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment