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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top