Readonly field for class type

Simen Kjærås simen.kjaras at gmail.com
Thu Mar 15 10:55:34 UTC 2018


On Thursday, 15 March 2018 at 10:16:49 UTC, 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
>>     }
>> }

You can do this:

class B {
     private A _a;
     @property const(A) a() { return _a; }

     this() {
         _a = new A();
         _a.updateValue();
     }
}

--
   Simen


More information about the Digitalmars-d-learn mailing list