Lazily evaluated property pointing to read only object

Basile B. via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Sep 24 03:16:34 PDT 2016


On Saturday, 24 September 2016 at 09:08:52 UTC, mikey wrote:
> I'm trying to figure out how to best write a class with a 
> property that is only evaluated when it's called for the first 
> time. And that returns an object which shouldn't be modifiable 
> a part of the owning class.
>
> I've had a go at doing something like this but am not very sure 
> if this is how to go about it.
> [...]
>
>
>         const(Obj) lazily() {
>             if (_o is null) {
>                 _o = new Obj("working " ~ _s);
>             }
>             return cast(const(Obj)) _o;
>         }
>     }

You don't need to cast, from "mutable" to "const" is implicit:
https://dlang.org/spec/const3.html#implicit_conversions


More information about the Digitalmars-d-learn mailing list