Skip to content

Should primary constructors for structs use named parameters, positional parameters, or allow either? #2365

Closed
@leafpetersen

Description

@leafpetersen

In the struct and extension struct proposal (#2360), the proposal adds primary constructors to structs. The generated primary constructor uses positional parameters, but there is discussion of the alternative approach of using named parameters. That is, the proposal is that the following:

struct Foo(int x, int y = 3);

is treated as roughly equivalent to:

class Foo {
  final int x;
  final int y;
  Foo(this.x, [this.y = 3]);
}

An alternative is to have the generated constructor use named parameters:

class Foo {
  final int x;
  final int y;
  Foo({required this.x, this.y = 3});
}

When @munificent has scraped corpuses of code before, I believe his conclusion is that code is split fairly evenly as to which form to use.

We could also choose to allow the user to specify: that is, we could allow the primary constructor to list zero or more parameters inside of braces, which would then become named parameters.

struct Foo(int x); // Constructor is Foo(this.x)
struct Bar({int x}); // Constructor is Bar({required this.x})
struct Baz(int x, {int y = 3}); // Constructor is Baz(this.x, {this.y = 3});

There are some obvious restrictions around the combinations of optional and named parameters, but otherwise I think this works out fine.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions