Friday, September 14, 2012

Simplify your constructors and top-level variables

The Dart mailing list was treated to some very good news today. Kasper Lund informed us that lazy init of statics and top-level variables is ready for use!

Kasper writes:

We now have one of the major new language features of M1 implemented
across the board. That's right -- you can now use lazy initialization
for top-level and static variables (both final and non-final). This
means that the restriction that used to force the initialization
expression for such a variable to be a compile-time constant is no
more. You can now write:

// Top-level.

final worklist = new Queue();
var compiler = new Compiler(worklist);

main() {
  compiler.compile();
}
and both worklist and compiler will be initialized on first access.

We've also lifted the restriction for instance fields so the following
code now runs just fine:

class Cache {
  final Map table = new Map();
  Logger log = new Logger();
  ...
}


as long as the initialization expressions do not refer to [this]. Such
expressions are evaluated when the object is created (not lazily on
first access as we do for static and top-level variables), but it cuts
down on the need for lengthy initializer lists in your constructors.

As always, you can join the Dart mailing list or ask questions on Stack Overflow.