Question on Immutability
Merlin Diavova
md at mdiavov.com
Mon Aug 30 23:27:07 UTC 2021
Hi All,
I'm trying to understand immutability in D and it seems a bit odd.
I'm coming from dynamic languages so please forgive my ignorance
and dynamic language-isms.
I want to have a base `Project interface` and then extend other
more specific interfaces from that such as `DockerEnabledProject
interface`, `NetworkEnabledProject interface` etc.
The interface implementations are immutable. I have defined some
methods that allows one to change specific properties and return
a new instance of the implementation.
```d
immutable interface Project
{
string name();
immutable(Project) withName(string name); // Returns a new
instance
}
immutable class ShellScriptCLI : Project
{
private string _name, _slug;
private DirectoryPath _directory;
string name()
{
return this._name;
}
immutable(Project) withName(string name)
{
return new immutable ShellScriptCLI(name, this._slug,
this._directory);
}
}
...
auto project = new immutable ShellScriptCLI("Project One",
"project-one", projectPath);
auto modifiedProject = project.withName("G2 Project");
assert(modifiedProject.name == "G2 Project");
```
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.
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.
Look forward to your help.
Thanks
Merlin
More information about the Digitalmars-d-learn
mailing list