proposal: short => rewrite for function declarations

Steven Schveighoffer schveiguy at gmail.com
Sat Oct 10 17:40:45 UTC 2020


On 10/10/20 6:25 AM, Andre Pany wrote:
> On Saturday, 10 October 2020 at 10:18:15 UTC, claptrap wrote:
>> On Friday, 9 October 2020 at 14:44:25 UTC, Adam D. Ruppe wrote:
>>> After a brief chat yesterday, I slapped this together:
>>>
>>> https://github.com/dlang/dmd/pull/11833
>>>
>>> In short, in a function declaration, it rewrites `=> ...;` into `{ 
>>> return ...; }`
>>>
>>> One benefit is shorter property accessors:
>>>
>>>     private int _x = 34;
>>>     @property x() => _x;
>>>     @property x(int v) => _x = v;
>>>
>>> But it also works basically anywhere
>>>
>>>     bool isNull() => this is null;
>>>     auto identity(T)(T a) => a;
>>>     @property y() in(true) => _x; // contracts still work too
>>>
>>> So it just extends the existing lambda shorthand to full declarations 
>>> too.
>>>
>>> See more in the PR description and the test case there.
>>
>> From the recent discussions I got the impression that needless syntax 
>> sugar shouldn't be added any more. To get new features in it needs to 
>> be something that cant be done with existing language features, or it 
>> needs to fix something.
>>
>> So doesn't this just add more "stuff" for no meaningful benefit?
>>
>> I couldnt care less about
>>
>> @property x() => _x;
>>
>> vs
>>
>> @property x() { return -x; }
>>
>> cause the important thing to me is that my code is simple, readable, 
>> expressive, i dont care about saving 7 chars on a one liner.
> 
> I assume, if you follow the style guide, the second example should be 
> written with 4 lines:
> 
> @property x()
> {
>      return -x;
> }
> 
> While the proposal from Adam is a 1 liner also from a style guide 
> perspective:
> 
> @property x() => _x;
> 
> (Yes, this is nitpicking... but for me the reason why I like the proposal).
> 

The D style guide is here:

https://dlang.org/dstyle.html

Indeed, it says you should always use separate lines for braces for all 
functions. But I think even Phobos/Druntime don't always follow this 
convention. We should change it so property functions and/or simple 
"return exp" functions do not need to be multiple lines.

This is not a reason to accept a language change, at all. Just change 
the style guide.

-Steve


More information about the Digitalmars-d mailing list