Lazily evaluated property pointing to read only object
mikey via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Sep 24 02:08:52 PDT 2016
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.
class Obj {
string _s;
this() {
this("");
}
this(string s) {
_s = s;
}
@property string desc() const { return _s; }
@property void desc(string s) { _s = s; }
override string toString() const {
return _s;
}
}
class ConstProp {
Obj _o;
string _s;
this(string s) {
_s = s;
}
const(Obj) lazily() {
if (_o is null) {
_o = new Obj("working " ~ _s);
}
return cast(const(Obj)) _o;
}
}
void main() {
auto c = new ConstProp("test");
writeln(c.lazily);
writeln(c.lazily.desc);
}
More information about the Digitalmars-d-learn
mailing list