Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Final and top-level lazy initialization

Tags:

dart

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.

like image 798
JAre Avatar asked May 07 '14 07:05

JAre


2 Answers

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.

like image 127
lrn Avatar answered Oct 04 '22 03:10

lrn


finalClassVariable is an instance variable not a class variable. To make it a class variable you have to prepend static.

like image 27
Günter Zöchbauer Avatar answered Oct 04 '22 03:10

Günter Zöchbauer