Question on Immutability

Mike Parker aldacron at gmail.com
Tue Aug 31 00:50:46 UTC 2021


On Monday, 30 August 2021 at 23:27:07 UTC, Merlin Diavova wrote:
>
> ```
> After playing around the above works, Great! However I have 
> some questions
>
> First, why do the interfaces have to be defined as `immutable 
> interface`?
> The interfaces cannot be changed at runtime or instantiated.

It isn't required. And that's related to the answer to the next 
question.

>
> Secondly, why does defining the return type for withName as 
> `Project` give the `Error: 'immutable' method 
> 'winry.project.Project.name' is not callable using a mutable 
> object`. However changing it to `immutable(Project)` works as 
> expected.
>

Applying immutable to a class or interface does not make 
instances immutable. It makes member functions callable on 
immutable instances. Example:

```d
import std.stdio;

interface Foo {
     void bar() immutable;
}

class Baz : Foo {
     void bar() immutable { writeln("Boo!"); }
}

void main()
{
     immutable(Baz) b = new Baz;
     b.bar();

}
```

Notice my application of immutable on the declarations of the 
member functions. This means that the `bar` function is callable 
through immutable instances of `Foo`.

When you apply immutable to the interface declaration, it has the 
effect of applying it to every member function. You can see that 
from the compilation error output when we modify the above to 
this:

```d
import std;

immutable interface Foo {
     void bar();
}

class Baz : Foo {
     void bar() { writeln("Boo!"); }
}

void main()
{
     immutable(Baz) b = new Baz;
     b.bar();

}
```

```d
onlineapp.d(7): Error: class `onlineapp.Baz` interface function 
`void bar() immutable` is not implemented
```

Member functions marked as immutable can be called on both 
mutable and immutable instances. Member functions without it can 
only be called on mutable instances.

This applies to const as well.


More information about the Digitalmars-d-learn mailing list