Last active
June 9, 2020 16:43
-
-
Save RedBrogdon/cc35655cf10b30a594e979f2e81fa3ab to your computer and use it in GitHub Desktop.
Snippet 10: Late circular references
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
// The `late` keyword can be really helpful | |
// for tricky patterns like circular | |
// references. Here are two objects that | |
// need to maintain non-nullable references | |
// to each other. Try using the `late` | |
// keyword to fix this code. | |
class Team { | |
final Coach coach; | |
} | |
class Coach { | |
final Team team; | |
} | |
void main() { | |
final myTeam = Team(); | |
final myCoach = Coach(); | |
myTeam.coach = myCoach; | |
myCoach.team = myTeam; | |
print ('All done!'); | |
} | |
// When you added `late`, did you remove | |
// `final`? If so, you don't have to! Late | |
// fields can also be final: you set their | |
// values once, and after that they're | |
// read-only. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment