Last active
June 9, 2020 16:43
-
-
Save RedBrogdon/1680b2b3f4d50abc9fa70148b6811b27 to your computer and use it in GitHub Desktop.
Snippet 9: The late keyword
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
// Sometimes fields in a class *should* be | |
// non-nullable, but can't be assigned a | |
// value right away. For cases like that, | |
// use the `late` keyword. It's a way to | |
// tell Dart that: | |
// | |
// * You aren't going to assign that | |
// field a value right away. | |
// * But you *are* going to assign it a | |
// value later. | |
// * And you'll make sure it's assigned a | |
// value before it's accessed. | |
// | |
// If you declare a field `late` and it's | |
// read before it has a value, a | |
// `LateInitializationError` is thrown to | |
// let you know what went wrong. | |
// | |
// Try using the `late` keyword to | |
// correct the following code. For a | |
// little extra fun afterward, try | |
// commenting out the line that sets | |
// `description`! | |
class Meal { | |
String description; | |
void setDescription(String str) { | |
description = str; | |
} | |
} | |
void main() { | |
final myMeal = Meal(); | |
myMeal.setDescription('Feijoada!'); | |
print(myMeal.description); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment