Getter an lvalue and cannot be modified

Steven Schveighoffer schveiguy at yahoo.com
Tue May 29 21:59:28 UTC 2018


On 5/27/18 5:23 AM, IntegratedDimensions wrote:
> C[] c;
> @property C[] get() { return c; }
> 
> get ~= something;
> 
> errors out, yet
> 
> auto q = get;
> q ~= something;
> 
> is fine.

It's "fine", but not doing what you may expect.

This appends an element to q, but does nothing to c.

While an array is not exactly a value type, it's also not exactly a 
reference type. This is why the compiler complains -- your original code 
will append an element and then throw that addition away.

> Why is D thinking that ~= is being applied to get, the function, rather 
> than what it returns?

When I try this, it says "get() is not an lvalue and cannot be 
modified", which seems to indicate that the expression get() (meaning 
what it returns) is not an lvalue. While it's a bit ambiguous in this 
case, a more complicated expression would be self-explanatory. Maybe the 
error message could be prepended with 'the expression' to make it clearer.

> When I converted a field in to a property, an AA, it is returning null 
> rather than being initialized by default.

AAs are initialized as null, not sure what you are expecting here? An 
example may clear things up.

> Seems like properties are 
> broke. I'd expect a property getter to behave, for all intents and 
> purposes as if it were field. I shouldn't have to have a temp variable 
> to be able to use it as such.

You don't normally, but if you want to treat it as an lvalue, 
unfortunately, you do.

The workaround is to spell things out:

prop = prop + 1; // instead of prop += 1

But this doesn't work in all cases.

-Steve


More information about the Digitalmars-d-learn mailing list