Skip to content

Instantly share code, notes, and snippets.

@antonmoiseev
Forked from anonymous/main.dart
Last active December 24, 2015 20:42
Show Gist options
  • Select an option

  • Save antonmoiseev/f6fb9ab899154efa6edb to your computer and use it in GitHub Desktop.

Select an option

Save antonmoiseev/f6fb9ab899154efa6edb to your computer and use it in GitHub Desktop.
Dart: lazily initialized class variable

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.

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