overiding mutable methods in immutable classes

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Nov 21 17:05:06 PST 2014


On Saturday, 22 November 2014 at 00:24:39 UTC, Eric wrote:
>
>
>
> immutable class X
> {
>    private int x;
>    this(int x) { this.x = x; }
>    ...
>    override size_t toHash(); // error: can't override mutable 
> method
> }
>
> Since toHash() cannot be overridden in an immutable class,
> is there a work-around?
>
> In other words,
>
> immutable X x1 = new immutable X(5);
> immutable X x2 = new immutable X(5);
>
> I would like for x1.toHash() to equal x2.toHash(),
> but this is not the case because toHash() cannot be overridden.

A class qualifier is a short-hand to qualify all members of the
class. That is, all fields and methods of an `immutable class`
are immutable. That's problematic here, because an immutable
method cannot overload a non-immutable method, and Object.toHash
is not immutable.

If you need to do override a non-immutable method, don't mark the
whole class as immutable. Instead, mark everything individually.
And make toHash const, not immutable.

class X
{
      private immutable int x;
      this(int x) immutable { this.x = x; }
      override size_t toHash() const {...}
}

But think about if enforced immutability is really what you want.
You don't need to mark the fields immutable to be able to
construct immutable Xs. A `pure` constructor is handy, as it can
construct both mutable and immutable objects.

class X
{
      private int x;
      this(int x) pure { this.x = x; }
}
void main()
{
      auto m = new X(5);
      auto i = new immutable X(5);
}

> Note also that (x1 != x2) even though they should be equal (I 
> think...)

By default, equality of objects is defined as identity. That is,
an Object is equal only to itself. Override opEquals to change
that.


More information about the Digitalmars-d-learn mailing list