how to declare an immutable class?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Aug 11 13:04:38 PDT 2016


On Thursday, August 11, 2016 10:56:59 Charles Hixson via Digitalmars-d-learn 
wrote:
> I want to declare a class all instances of which will be immutable, and
> all references to which will be inherently immutable (so that I don't
> need to slip a huge number of "immutable" statements in my code).
>
> This is surely possible, because string acts just that way, but I can't
> figure out how to do this.
>
> immutable class    Msg  {    this(...) immutable{...} ... }
>
> doesn't work that way, as when I do
>
> Msg m = new Msg (...);
>
> I get:
>
> Error: incompatible types for ((this.m) - (m)): 'immutable(Msg)' and
> 'cellram.Msg'
>
> and
>
> Error: immutable method cellram.Msg.this is not callable using a mutable
> object
>
>
> Does anyone know the correct approach?

There is no such thing as an immutable class. You can have an instance of a
class that's immutable, and you can make it so that all of the members of a
class are immutable, but you're still going to need to use the keyword
immutable with the type to indicate that it's immutable. If you do

immutable class C
{
    ...
}

that's the same as

immutable
{
    class C
    {
        ...
    }
}

It makes it so that all of the members of the class are immutable, but
if you use C in the code, it won't be immutable - only immutable C will be
immutable. Now, you could use an alias to reduce your typing. e.g.

alias IC = immutable C;

and then whenever you use IC, it will be replaced with immutable C by the
compiler, but anywhere you use C rather than the alias, you're going to need
to put immutable on it if you want it to be immutable. So, your code could
become something like

immutable class _Msg
{
    // the immutable on the class made this immutable. There's no need
    // to mark it with immutable.
    this(...)
    {
    }

    ...
}

alias Msg = immutable _Msg;

and then when you do

auto msg = new Msg;

you'll get an immutable(_Msg).

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list