Readonly field for class type

Ali Çehreli acehreli at yahoo.com
Thu Mar 15 22:39:37 UTC 2018


On 03/15/2018 03:16 AM, Andrey wrote:
> Hello, is there way to declare read only field for class type with 
> ability to call inner non constant methods? i.e.:
> 
>> class A {
>>     int value = 12;
>>     void updateValue() {
>>         value = 13;
>>     }
>> }
>>
>> class B {
>>     const A a;
>>
>>     this() {
>>         a = new A();
>>         a.updateValue();  // error: mutable method is not callable 
>> using const object
>>     }
>> }
> 
Another option is assigning a pre-made A to the member:

class A {
     int value = 12;
     void updateValue() {
         value = 13;
     }
}

// Magic recipe is moved here:
A makeA() {
     auto a = new A();
     a.updateValue();
     return a;
}

class B {
     const A a;

     this() {
         a = makeA();
     }
}

void main() {
     auto b = new B();
}

Which can be compressed into a lambda in the constructor:

     this() {
         a = {
             // This 'a' is a local variable inside the lambda:
             auto a = new A();
             a.updateValue();
             return a;
         }();
     }

Ali


More information about the Digitalmars-d-learn mailing list