What is the state of @property?

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Mon Aug 29 08:40:51 UTC 2022


On 8/28/22 6:36 PM, Steven Schveighoffer wrote:
> On 8/28/22 9:43 AM, Salih Dincer wrote:
>> On Thursday, 25 August 2022 at 03:49:07 UTC, Steven Schveighoffer wrote:
>>> It does just about nothing. The only discernable difference is `typeof`:
>>>
>>> ```d
>>> struct S
>>> {
>>>     int prop1() { return 1; }
>>>     @property int prop2() { return 2; }
>>> }
>>>
>>> pragma(msg, typeof(S.prop1)); // int()
>>> pragma(msg, typeof(S.prop2)); // int
>>> ```
>>
>> The function has parameters, the difference you're pointing isn't even 
>> visible :)
>> ```d
>> struct S
>> {
>>      int prop1(int a) { return a; }
>>      @property int prop2(int b) { return b; }
>> }
>>
>> pragma(msg, typeof(S.prop1(1))); // int
>> pragma(msg, typeof(S.prop2(2))); // int
>> ```
> 
> You are asking for the type of the expression which calls the function. 
> (i.e. `typeof(s.prop2(1))` instead of `typeof(s.prop2)`. However, 
> `typeof(s.prop2)` is going to fail, because the compiler is requiring 
> property functions to be used when using `typeof` (and only when using 
> `typeof`).
> 
> I'm trying to tell you this is the *only thing `@property` does*. In all 
> other cases, it's indistinguishable from a normal function/method.

I think this should be immortalized and made very clear in the docs. 
It's an FAQ. (FWIW it's also a sign that the feature is not very helpful.)

One possibility to make it more useful would be to have @property 
disallow function signatures that cannot possibly be used as properties 
(e.g. multiple non-defaulted parameters).

Also properties that return UDTs by value are suspect because they lead 
to confusing code. Consider:

struct Widget { int a; }
@property Widget w() { return Widget.init; } // should be disallowed
void main() {
     w.a = 42; // does nothing, looks like it's assigning a value
}

Assigning values to fields of rvalues is a distinct long-standing problem.


More information about the Digitalmars-d mailing list