On Saturday, 21 February 2015 at 06:38:18 UTC, rumbu wrote:
Often I'm using the following code pattern:

class S
{
   private SomeType cache;

   public SomeType SomeProp() @property
   {
      if (cache is null)
        cache = SomeExpensiveOperation();
      return cache;
   }
}

Is there any way to mark SomeProp() as const? Because I want to call somewhere const(S).SomeProp, which for the outside world is must be "const", returning just a value, even that internaly it modifies the internal S structure.

AFAIK it is unsafe and not recommended, but this works for me:

----
import std.stdio;

class Foo {
    void say(string s) const {
        writeln(s);
    }
}

class Bar {
    Foo f;

    const(Foo) getFoo() const {
        if (!f)
            cast() this.f = new Foo();
        return f;
    }
}

void main() {
    Bar b = new Bar();
    const Foo f = b.getFoo();
    f.say("Hello");
}
----

Reply via email to