why properties don't support +=, -= ... operators?

via Digitalmars-d digitalmars-d at puremagic.com
Tue May 23 10:38:18 PDT 2017


On Tuesday, 23 May 2017 at 16:43:33 UTC, Stanislav Blinov wrote:
> On Tuesday, 23 May 2017 at 16:13:19 UTC, Andrey wrote:
>> Hello! I am constantly worried about this flaw, why this bug 
>> still was not resolved: 
>> https://issues.dlang.org/show_bug.cgi?id=8006
>> e.g. in Kotlin I can write property like this:
>>> class Example {
>>>     var value: Int = 0
>>>         set(v) {
>>>             field = v
>>>         }
>>>         get() = field
>>> }
>>>
>>> fun main() {
>>>     var e = Example()
>>>     e.value = 10
>>>     e.value += 1
>>>     println(e.value)
>>
>> And it will work!
>>
>> In D I can write something like this:
>>> class Example {
>>>     private int value_; @property {
>>>         void value(in int val) {
>>>             value_ = val;
>>>         }
>>>         int value() {
>>>             return value_;
>>>         }
>>>     }
>>> }
>>
>> That's great, but еhe absence of in-place operators creates 
>> additional problems sometimes, and using ref I think not a 
>> good idea, because of inconsistency.
>
> struct Foo
> {
>     private int value_;
>
>     void value(int v) { value_ = v; }
>     ref inout(int) value() inout { return value_; }
> }
>
> void main()
> {
>     import std.stdio;
>     Foo foo;
>     foo.value += 150;
>     writeln(foo.value);
> }
>
> Which inconsistency do you mean? Not calling a function when 
> applying an operator to a property?

The problem is that if you return by ref you loose the ability to 
intercept the setting of the value, i.e. you're no better than 
just making the field public.

AFAIU the OP, he's asking for the following lowering:

e.value += 42;
//   ^
//   v
e.value(e.value() + 42);

However, note that in general such lowering may not always be 
possible or desirable. For example:

e.someContainerProperty ~= new Item();
//   ^
//   v
e.someContainerProperty(e.someContainerProperty() ~ new Item());




More information about the Digitalmars-d mailing list