Search code examples
immutabilityd

How to create a re-assignable reference to an immutable class?


How do I create a reference to immutable classes, but while keeping the ability to reassign the reference, sort of like string?

import std.stdio;

immutable class Test {
    string test(){
        return "test";
    }
}

void main(){
    auto test = new Test;
    writeln(test.test);
}

This causes an error, because the created instance is not immutable:

test.d(14): Error: immutable method test.Test.test is not callable using a mutable object

new immutable doesn't work either, because the resulting variable cannot be assigned a new one afterwards.

immutable(Test)* would work, but is there a way avoiding pointers?


Solution

  • Use std.typecons.Rebindable http://dpldocs.info/experimental-docs/std.typecons.Rebindable.html#examples

    import std.typecons;
    class Widget { int x; int y() const { return x; } }
    auto a = Rebindable!(const Widget)(new Widget);
    // Fine
    a.y();
    // error! can't modify const a
    // a.x = 5;
    // Fine
    a = new Widget;