Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining immutable and normal constructor in D?

Tags:

immutability

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;
}
like image 959
Scintillo Avatar asked Mar 21 '23 02:03

Scintillo


1 Answers

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.

like image 130
Adam D. Ruppe Avatar answered Apr 01 '23 07:04

Adam D. Ruppe