Please help me to understand what it exactly means:
Quote from the "Chapter 2. A Tour of the Dart Language"
A local, top-level, or class variable that’s declared as final is initialized the first time it’s used
So this is my test code:
lazyTest(msg) => print(msg);
class Printer{
Printer(msg){
print(msg);
}
final finalClassVariable = lazyTest("final class variable");
}
var globalsAreLazy = lazyTest("top-level");
var lazyInitialized = lazyTest("lazy initialized");
void main() {
final localFinal = new Printer("local final");
var initialize = lazyInitialized;
}
Output:
final class variable
local final
lazy initialized
Both finalClassVariable
and localFinal
initialized and only globalsAreLazy
wasn't. lazyInitialized
was initialized on access as i expected.
Class variables is another name for static fields, so you need to make finalClassVariable
static for it to be lazy.
The text is incorrect on local variables. They are initialized when the declaration is executed, not lazily when it is first read.
Non-static class fields with initializer expressions are initialized when a constructor is called. They are not lazy.
finalClassVariable
is an instance variable not a class variable. To make it a class variable you have to prepend static
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With