Static member function returning immutable slice; compiler error: without this cannot be immutable

ag0aep6g anonymous at example.com
Thu Jul 5 20:00:28 UTC 2018


On 07/05/2018 09:43 PM, Ivo Maffei wrote:
> class Foo {
>      private static Foo[] fooSlice = new Foo[0]; //private static slice
> 
>      static immutable Foo[] getFooList() { //static method returning an 
> immutable slice
>          return fooSlice;
>      }
> }
> 
> However when compiling with dub I get the following error:
> 
> Error: function `main.Foo.getFooList` without this cannot be immutable

If you want to return an `immutable Foo[]`, you have to write the 
signature like this:

     static immutable(Foo[]) getFooList()

Otherwise, the `immutable` qualifier applies to the method itself 
instead of the `Foo[]` return type. But a static method can't be 
immutable, so you get the error.

But it won't work even if you fix that, because mutable doesn't convert 
to immutable like that.

`immutable` means that the data can't ever change. Not even the owning 
Foo is allowed to change it. If you want to disallow changes from 
outside, but still allow the owning Foo to make changes, use `const`:

     static const(Foo[]) getFooList()


More information about the Digitalmars-d-learn mailing list