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

Ivo Maffei ivomaffei at gmail.com
Thu Jul 5 19:43:43 UTC 2018


I'm writing my first D program and I want to have a class which 
contains a private static list of objects.
Moreover such list should be visible from outside the class, so I 
wrote a get method which returns such list as immutable (so that 
the list cannot be modified outside the class).
Finally such method should be static since the list is static and 
therefore I should not need an object to access such list.

Here is the code:

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

I noted that the error goes away when I remove the static or 
immutable qualifier.

Thanks a lot for any help.


More information about the Digitalmars-d-learn mailing list