Cached property (translate Python -> D)

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Jan 29 18:00:36 UTC 2019


On Tue, Jan 29, 2019 at 05:13:16PM +0000, Victor Porton via Digitalmars-d wrote:
> I've successfully implemented it myself:
> 
> ---
> import std.stdio;
> 
> mixin template Cached(string name, string baseName = '_' ~ name) {
>     mixin("private typeof(" ~ baseName ~ ") " ~ name ~ "Cache;");
>     mixin("private bool " ~ name ~ "IsCached = false;");
>     mixin("@property typeof(" ~ baseName ~ ") " ~ name ~ "() {\n" ~
>           "if (" ~ name ~ "IsCached" ~ ") return " ~ name ~ "Cache;\n" ~
>           name ~ "IsCached = true;\n" ~
>           "return " ~ name ~ "Cache = " ~ baseName ~ ";\n" ~
>           '}');
> }
> 
> struct C {
>     @property int _f() { writeln("Got!"); return 2; }
>     mixin Cached!"f";
> }
> 
> void main(string[] args)
> {
>     C x;
>     writeln(x.f);
>     writeln(x.f);
> }
> ---
> 
> I think, we should add this to the standard library. What do you think?

You could have just used std.typecons.Nullable instead of reimplementing
it yourself:

	private Nullable!T _myField;
	@property T myField() {
		if (_myField.isNull)
			_myField = ...; // initialize it here
		return _myField;
	}


T

-- 
Elegant or ugly code as well as fine or rude sentences have something in common: they don't depend on the language. -- Luca De Vitis


More information about the Digitalmars-d mailing list