Simple immutable example doesn't work - why???

TheFlyingFiddle theflyingfiddle at gmail.com
Mon Nov 11 16:57:16 PST 2013


On Tuesday, 12 November 2013 at 00:43:34 UTC, Louis Berube wrote:
> Edit for (hopefully) better readability:
>
> Simple example:
>
> // file immutable_example.d
>
> immutable class Test
> {
>     public:
>         this(in uint value)
>         {
>             this.value = value;
>         }
>         unittest
>         {
>             auto t = new Test(4); // "Error: immutable method
>                                   // immutable_example.Test.this
>                                   // is not callable using
>                                   // a mutable object"
>             assert (t.value == 4);
>         }
>     private:
>         uint value;
> }

> Assuming this is not a compiler issue, what am I missing?
> Integer literal is about as immutable as it gets.

Well the issue is that new Test(5) is not an immutable object.
To create an immutable object use new immutable Test(5).

class Test
{
     private uint value;
     //Ctor needs to be immutable to create immutable objects.
     this(uint value) immutable
     {
	this.value = value;
     }
}

unittest
{
     //use the immutable keyword.
     auto a = new immutable Test(5);
     //or
     auto b = new immutable(Test)(6);
     //Will not work
     //auto c = new Test(7); //new Test not an immutable object.
}


More information about the Digitalmars-d-learn mailing list