Skip to content

Instantly share code, notes, and snippets.

Created December 24, 2015 20:30
Show Gist options
  • Select an option

  • Save anonymous/9a8b9b495f886fd25cf9 to your computer and use it in GitHub Desktop.

Select an option

Save anonymous/9a8b9b495f886fd25cf9 to your computer and use it in GitHub Desktop.
white-poetry-2771

white-poetry-2771

The example illustrates the following statement from The Dart Programming Language book (http://amzn.com/0321927702):

Class variables are initialized lazily; the initializer of a class variable is executed the first time its getter is invoked — that is, the first time one attempts to read the variable

When foo is printed the first time, its value is 0. Then we access the A.bar field and its initializer updates the foo's value. The second time we print foo its value is already 1.

Find the runnable version at DartPad.

Created with <3 with dartpad.dartlang.org.

var foo = 0;
class A {
static var bar = (foo = 1);
}
void main() {
print(foo); // 0 since A.bar hasn't been ever accessed yet
A.bar; // A.bar's initialization expression is lazily evaluated
print(foo); // 1 since A.bar has been accessed already
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment