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

Adam D. Ruppe destructionator at gmail.com
Thu Jul 5 19:59:05 UTC 2018


On Thursday, 5 July 2018 at 19:43:43 UTC, Ivo Maffei wrote:
> 	private static Foo[] fooSlice = new Foo[0]; //private static

That initializer is useless, don't do that, just use the slice.

> 	static immutable Foo[] getFooList() { //static method 
> returning an immutable slice

Actually, that's a static immutable *method* returning a mutable 
slice. It is like you wrote:

immutable {
    // bunch of methods here
}

so it is applying to this. To make it apply to the return, use 
parens around it:


static immutable(Foo)[] getFooList() {}

or

static immutable(Foo[]) getFooList() {}


the former is a mutable array of immutable objects and the latter 
is all immutable


More information about the Digitalmars-d-learn mailing list