proposal: short => rewrite for function declarations
Steven Schveighoffer
schveiguy at gmail.com
Fri Oct 9 19:11:44 UTC 2020
On 10/9/20 10:44 AM, 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.
It's kind of weird. You usually name a lambda outside the definition. Like:
auto x = () => _x;
But having the name makes it unambiguous from an actual lambda. You
aren't saving much though, I do a lot of one-liners like:
@property x() { return _x; }
Compare to:
@property x() => _x;
It's not *that* much savings...
A lambda can also have no type for the parameter:
(v) => _x + v;
(T)(T v) => _x + v; // equivalent to this
Which is super-useful and less verbose. But in this syntax, I'm guessing
it's going to interpret v as a type?
-Steve
More information about the Digitalmars-d
mailing list