Lazily Initialized Variables that are Compatible with const/immutable
Vijay Nayar
madric at gmail.com
Fri Nov 18 17:22:08 UTC 2022
On Friday, 18 November 2022 at 11:06:44 UTC, Timon Gehr wrote:
> On 18.11.22 11:59, Timon Gehr wrote:
>>
>>
>>> which is used to optimize performance (in Dart, `const` is
>>> closer to D's `immutable`).
>>
>> Actually, it is closer to `static immutable`.
>
> (But even that analogy has significant limitations, e.g.,
> transitivity of Dart `const` is often checked at runtime, even
> if it is completely obvious during type checking that an
> assignment is not going to work.)
It's not as complicated as you are making it out to be. The
purpose of Dart's late variables is as they describe:
```
When you mark a variable as late but initialize it at its
declaration, then the initializer runs the first time the
variable is used. This lazy initialization is handy in a couple
of cases:
* The variable might not be needed, and initializing it is
costly.
* You’re initializing an instance variable, and its initializer
needs access to this.
```
The same use-cases would apply in D, these situations are
programming-language agnostic. For example, you are building a
complicated geometric library object (as is the case in the S2
Geometric library), and it contains a complex index data
structure which will be used to organize the data before it is
written to disk. When data is being written to disk, you want
this variable to be computed only once, it will not change once
used, and you would still like to use these objects in const
contexts that will not change the values. However, if you are not
calling the methods that write to disk, then computing the index
isn't necessary and can be avoided.
There are many cases where lazy initialization can be used to
avoid costly setup, but currently in D, if you use lazy
initialization, you must immediately rewrite all your code and
avoid ever using `const`, because it might trigger initialization
of lazy variables. This is especially silly for functions like
"print" or "writeToDisk", which absolutely do not modify the
classes at hand.
More information about the Digitalmars-d
mailing list