Trailing commas in constructor arguments?

monarch_dodra via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun May 4 03:23:29 PDT 2014


On Sunday, 4 May 2014 at 10:04:26 UTC, Gary Willoughby wrote:
> In the following snippet is the line marked WOAH legal? The 
> compiler doesn't complain about the trailing comma in the 
> constructor arguments.
>
> import std.stdio;
>
> class Foo
> {
> 	public this(string foo)
> 	{
> 	}
> }
>
> void main(string[] args)
> {
> 	auto foo = new Foo("bar", ); // <-- WOAH
> }

Yes. As a rule of thumb, a single trailing comma is *always* 
legal. It allows for easier and uniform syntax for calls with 
lots of arguments:

new Foo(
   "bar1",
   "bar2",
   "bar3",
   "bar4",
);

This works for mostly anything: both calls and function 
declaration:

this(
     string arg1,
     string arg2,
     string arg3,
     string arg4,
)
{
    ...
}

It also works for arrays:
auto arr1= [
     1,
     2,
     3,
     4,
];

Or enums:
enum Letters
{
     A,
     B,
     C,
     D,
}

The advantage in all the above means no special case if you want 
to add, swap or comment a certain argument: They are all "equal" 
in terms of separator comma.

Finally, it makes mixins/generated code easier, since you don't 
have to worry about the "last argument" special case (though if 
you use "range formating": "%(%s,%)", it shouldn't matter).

--------

So long story short, yes, it is legal. And convenient. I've 
personally adopted it, and use it any time I list arguments 
vertically.


More information about the Digitalmars-d-learn mailing list