Effect of declaring a class immutable ?
Basile B. via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu May 26 07:59:29 PDT 2016
On Thursday, 26 May 2016 at 14:12:23 UTC, chmike wrote:
> I couldn't find any information about this on the dlang web
> site.
>
> What is the effect adding the immutable attribute to a class
> like this
>
> immutable class MyClass { ... }
>
> The compiler doesn't complain.
> Will it add the immutable attribute to all members ?
Since immutable is transitive everything in your class will be.
So basically the only thing you can do is
- create a new immutable(MyClass)
- sets the instances variables in the ctor.
- calls the method (which can't do anything on the variables).
And that's all, e.g:
----
immutable class Foo
{
int i;
this(int i){this.i = i;}
void method(){}
}
void main()
{
immutable(Foo) foo = new immutable(Foo)(1);
//foo.i = 8; // not possible since i is immutable
Foo foo1 = cast(Foo) foo; // cast away immutable from the
type.
//foo1.method; // not pissible since method is immutable
}
----
So it's more or less useless, unless you want to wrap some
variables in a class to simplify completion in the IDE or
whatever other reasons.
_________________
By the way the doc for "immutable class Stuff" is here:
https://dlang.org/spec/const3.html#immutable_type, it's a type
constructor. "immutable" is fully part of the type.
More information about the Digitalmars-d-learn
mailing list