Readonly field for class type

Seb seb at wilzba.ch
Thu Mar 15 13:48:35 UTC 2018


On Thursday, 15 March 2018 at 13:44:20 UTC, Seb wrote:
> On Thursday, 15 March 2018 at 10:57:52 UTC, Mike Parker wrote:
>> On Thursday, 15 March 2018 at 10:55:16 UTC, Mike Parker wrote:
>>
>>>
>>> class A {
>>>     private int _value = 12;
>>>
>>>     int value() @property { return _value; }
>>>     void updateValue() { value = 13; }
>>> }
>>>
>>> ...
>>> auto a = new A();
>>> writeln(a.value);
>>> a.updateValue();
>>> writeln(a.value);
>>
>> Sorry. I overlooked that B.a is const.
>
> It still works, the `value` just needs to be `const` (or 
> `inout`) and _value needs to be used in updateValue:
>
> class A {
>     private int _value = 12;
>
>     int value() const { return _value; }
>     void updateValue() { _value = 13; }
> }
>
>
> auto a = new A();
> writeln(a.value);
> a.updateValue();
> writeln(a.value);
>
>
> In action: https://run.dlang.io/is/Tk1rY1
>
> @Robert: If you need this a lot, the accessors package might be 
> interesting to you:
>
> https://code.dlang.org/packages/accessors

... and I didn't add `const` to A

-> https://run.dlang.io/is/QObN1w

but better have a look at Simen's response 
(https://forum.dlang.org/post/ottyywbmrwgfabgpfehk@forum.dlang.org), it's what you are looking for. I read too quickly and only have of it :/


More information about the Digitalmars-d-learn mailing list