Scintillo
Scintillo

Reputation: 1704

Combining immutable and normal constructor in D?

Is it possible to write one constructor instead of two and still be able to create both normal and immutable objects? It is a lot of repetitive work to write both normal and immutable constructor.

class ExampleClass
{
    void print() const
    {
        writeln(i);
    }

    this(int n)
    {
        i = n * 5;
    }

    this(int n) immutable
    {
        i = n * 5;
    }

private:
    int i;
}

Upvotes: 4

Views: 119

Answers (1)

Adam D. Ruppe
Adam D. Ruppe

Reputation: 25605

Make the constructor pure and it can implicitly convert to any qualifiers.

this(int n) pure
{
    i = n * 5;
}

auto i = new immutable ExampleClass(2);
auto m = new ExampleClass(3);

Documented here: http://dlang.org/class.html "If the constructor can create unique object (e.g. if it is pure), the object can be implicitly convertible to any qualifiers. "

BTW: the return value of other pure functions implicitly convert too.

// returns mutable...
char[] cool() pure {
    return ['c', 'o', 'o', 'l'];
}

void main() {
    char[] c = cool(); // so this obviously works
    string i = cool(); // but since it is pure, this works too
}

Same principle at work there, it is unique so it can be assumed to be shared or immutable too.

Upvotes: 7

Related Questions