Description
[Update: There is considerable interest on the team in adding primary constructors as a general feature. This original discussion issue has been repurposed as the tracking issue for the general feature request.]
Introduction
Primary constructors is a feature that allows for specifying one constructor
and a set of instance variables, with a concise and crisp syntax. Consider this
Point
class defined using the current class syntax for the constructor and fields:
class Point {
int x;
int y;
Point(this.x, this.y);
}
With the primary constructor feature, this class can defined with this much shorter syntax:
class Point(int x, int y);
Discussion
[original issue content below]
In the proposal for structs and extension structs, I propose to add primary constructors to structs. Briefly, the class name (or the type parameter list if any) may/must be followed by a parenthesized list of variable declarations as such:
struct MyStruct(int x, int y) {
// members here
}
In the struct proposal, these are always final by default, and are restricted in various ways (i.e. they may not be late, they may not be const). They are allowed to declare initializers, which are used to generate default initialization values.
This issue is to discuss the possibility of splitting this out, and making it a general feature for classes as well.
Initial points in favor of this include:
- It would be consistent, and nice to have this available for classes
- It makes structs less different from classes
Initial points against include:
- Resolving the tension between the desire to have final by default for structs, and the existing mutable by default behavior in classes.
- Classes support richer superclass structure that may make specifying how the generated constructor works more complicated
- Dealing with const constructors here seems more complicated than in the data class case.
Metadata
Metadata
Assignees
Labels
Type
Projects
Status