Blog

[Dart] Lazy Initialization

Published 1 min read

class Person { late int age = calculation(); void printAge() { print('age'); } } int calculation() { print('calculate'); return 30; } void main() { Person p = Person(); p.printAge(); print(p.age); }

The output of the source code above is as follows.

age calculate 30

A variable marked with the late keyword doesn't get its value right away; it gets assigned when the variable is referenced.
So when the Person() object is created, calculation() doesn't run.
The printAge() function runs and prints age,
and the moment we try to print p.age, calculation() runs and prints calculate.
Then 30 is assigned to age and 30 is printed.

Using the late keyword like this, so that a value isn't assigned right away but only when the variable is referenced, is like
initializing lazily and slowly, which is why it's called lazy initialization.

Comments

Leaving a comment stores your nickname (or GitHub profile info). Privacy policy

GitHub