dart-lang / dart-lang/language
Let record types have a constructor.
- Dominant language
- TeX
- Stars
- 2.9k
- Forks
- 239
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 14
Description
The only way to create a record value is a record literal. If you want some other function to create a record for you, you need to wrap that up as a function, `(int v1, String v2) => (v1, v2)`.
I think it could be useful to allow record types to be considered as having a `const` unnamed *generative constructor*, which can be torn off. Or called, if that's considered useful.
That would allow more easily creating a *function* which creates a record from arguments in the same order.
It may also be useful for using record types in places where a constructor is expected (potentially #2967), and if we add any future features which work on types with constructors, records would fit in (say if we ever allow calling constructor through type parameters, or let them have static interfaces).
Allowing a constructor to be torn off, from a specific record type, should not change the analysis of which record shapes are used by a program, although it would probably consider the shape used, even if the constructor is never called. (Unless the tear-off itself can be tree-shaken.)
It's not trivial to *access* the constructor directly, since you can't write `(int, int).new` (it's not in the grammar).
The workaround would likely be having a `typedef typeof = T;` and do `typeof<(int, int)>.new`. That's a reasonable enough workaround, and the type-alias could be useful in other ways too.
Calling it as, say, a super-constructor of an inline class would work directly.
(And if you have a `typedef Tuple2 = (T1, T2);` you can do `Tuple2(v1, v2)` and get the normal type inference applied.)
Contributor guide
Assessment
This issue has not been assessed yet.