On Thu, 15 May 2014 12:13:58 -0400, AntonSotov <nepuv...@rainmail.biz> wrote:

DMD 2.065
I do not know much English. sorry.

need to initialize immutable array  "_items"
//-------------------------------------------------------
module main;
import std.stdio;

class Zond {
   this() {
     foreach (i; 1..4) {
       _items ~= i;  // is expected ERROR
     }
   }

   immutable(int[]) _items;
}

int main(string[] args)
{
   // create
   auto zond = new Zond();
   // test output
   foreach (it; zond._items) {
     writeln(it);
   }
   return 0;
}
//-------------------------------------------------------
this method does not work:
Error: field _items initializing not allowed in loops or after labels.

Assign _items only once in the constructor.

immutable(int)[] tmp;

foreach(i; 1..4)
   tmp ~= i;

_items = tmp;

Make a small change, I add a nested function "addItem":
//-------------------------------------------------------
module main;
import std.stdio;

class Zond {
   this() {
     void addItem(in int value) {
       _items ~= value;  // OK ,  why?
     }

     foreach (i; 1..4) {
       addItem(i);
     }
   }

   immutable(int[]) _items;
}

int main(string[] args)
{
   // create
   auto zond = new Zond();
   // test output
   foreach (it; zond._items) {
     writeln(it);
   }
   return 0;
}
//-------------------------------------------------------
This method initialization works. why?
I do not understand the difference.

This should not work IMO.

-Steve

Reply via email to