Lazily Initialized Variables that are Compatible with const/immutable
Vijay Nayar
madric at gmail.com
Fri Nov 18 09:00:43 UTC 2022
On Thursday, 17 November 2022 at 22:01:21 UTC, Timon Gehr wrote:
> On 17.11.22 22:49, Vijay Nayar wrote:
>> On Thursday, 17 November 2022 at 15:33:47 UTC, razyk wrote:
>>> On 17.11.22 13:04, MorteFeuille123 wrote:
>>>>>
>>
>> While the solutions from razyk and Ali take care of lazy
>> initialization, with Ali's solution also having the benefit of
>> being thread-safe, none of these methods are actually
>> compatible with `const` or `immutable`, meaning that in any
>> case where lazy initialization is needed, you cannot have a
>> const class, you have to pick one or the other in the current
>> setup.
>
> Well, that's what `const` and `immutable` mean. If you need to
> restrict mutation in some other way, classic encapsulation
> works.
>
> Note that it is not all that often appropriate to use those
> qualifiers when writing traditional OO code.
In response to this argument, I would cite the Dart language's
implementation of `late` variables:
https://dart.dev/guides/language/language-tour#late-variables
To its core, Dart is fully object oriented, and it makes frequent
use of immutable and const values which is used to optimize
performance (in Dart, `const` is closer to D's `immutable`). The
mechanism presented in the link above demonstrates the concept of
lazy evaluation while also being compatible with const. The
variable is still const, however, the computation of its initial
and only value is deferred until its first usage.
More information about the Digitalmars-d
mailing list