how to declare an immutable class?
Mike Parker via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Aug 11 22:25:45 PDT 2016
On Friday, 12 August 2016 at 04:49:46 UTC, Charles Hixson wrote:
> It works, it's just not the syntax that I'd prefer. And it
> leaves me wondering exactly what
> immutable class Msg {...}
> was declaring.
This should demonstrate:
```
immutable class iMsg {
int getX() { return 10; }
}
class Msg {
int getX() { return 20; }
}
void main() {
auto msg1 = new immutable iMsg;
assert(msg1.getX() == 10);
auto msg2 = new immutable Msg;
assert(msg2.getX() == 20);
}
```
The line with msg2.getX() will fail to compile, because it's
calling a non-immutable method on an immutable object. Change the
declaration of Msg to the following and it compiles:
```
class Msg {
int getX() immutable { return 20; }
}
```
immutable class Foo { ... } is the same as declaring every member
of Foo as immutable, just as final class Foo { ... } makes every
method final.
More information about the Digitalmars-d-learn
mailing list