How can I do lazy variable initialization?

Ali Çehreli acehreli at yahoo.com
Sat Jan 9 20:35:52 UTC 2021


Explicit with a lambda:

import std;

int heavyLoadOperation() {
   writeln("Expensive!");
   return uniform(0, 10);
}

void main(string[] args) {
   const l = {
     bool inited = false;
     static int i;
     if (!inited) {
       i = heavyLoadOperation();
     }
     return i;
   }();

   if (args.length == 1) {
     writefln!"Using lazy variable: %s %s"(l, l);
   }
}

Getting help from memoize (this one is lovely):

alias lightLoadOperation = memoize!heavyLoadOperation;

   const l = lightLoadOperation();

And of course, the first approach can be wrapped in a type like C#'s 
lazy as well.

Ali



More information about the Digitalmars-d-learn mailing list