Lazily Initialized Variables that are Compatible with const/immutable

MorteFeuille123 MorteFeuille123 at ert.rt
Fri Nov 18 18:08:20 UTC 2022


On Thursday, 17 November 2022 at 15:33:47 UTC, razyk wrote:
> On 17.11.22 13:04, MorteFeuille123 wrote:
>>>
>>> Is there another way to perform lazy initialization that is 
>>> compatible with const/immutable, or is this needed as a 
>>> language feature?
>> 
>> No, this is needed as a bultin feature I'd say. I sometime 
>> think that since we can have local static variablbes, we could 
>> have local member variables. Similarly hiddden, only 
>> accessible through a getter, which replaces the need for a 
>> const member.
>
> module2.d
> ```
> import std.stdio;
>
> private string _lazy1;
>
> string compute(){
>   writeln("computing...");
>   return "_lazy1 val";
> }
>
> string lazy1(){
>   if (_lazy1 == null)
>     _lazy1 = compute();
>   return _lazy1;
> }	
> ```
>
> module1.d
> ```
> import std.stdio;
> import module2;
>
> void main() {
>   writeln(lazy1);
>   writeln(lazy1);
> }
> ```

No, I tought to this pattern:

     auto getLazyGlobal()
     {
         static int result; // global but only accessible in 
getLazyGlobal
         static bool done;  // ditto
         scope(exit) done = true;
         return done ? result : (result = compute())
     }

but applied to member variables.
That would require a new syntax or a new storage class

     struct S
     {
         auto getLazyMember()
         {
             int S.result;
             bool S.done;
             scope(exit) done = true;
             return done ? result : (result = compute())
         }
     }

so that `result` and `done` are well `S` members but only 
accessible in `getLazyMember()`.


More information about the Digitalmars-d mailing list