Lazily Initialized Variables that are Compatible with const/immutable

razyk user at home.org
Thu Nov 17 15:33:47 UTC 2022


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);
}
```



More information about the Digitalmars-d mailing list