Description
This issue raises the question whether we should resolve the invocation of a constructor for a class C
which is declared by several static extensions based on the constructor return type, or should we just report an error as soon as there are multiple extensions declaring constructors with the requested name?
Background: #3835 provides a proposal for generalizing extension
declarations such that they can contribute static members and constructors to an existing declaration (e.g., a class, an extension type, etc.), in a way that may resemble extension instance members (that is, "normal" members of the extension declarations that we have had in the language for several years). The same PR also provides a proposal where a new kind of declaration, static extension
, delivers the same affordances, but avoids conflating the semantics of extension
with new mechanisms and new syntax. We may prefer one or the other proposal, or something else altogether, but the following question seems relevant to them all (and I'll just use static extension
to refer to the kind of declaration that provides this feature):
A static extension
can declare a constructor for its so-called on-class, and it has an associated constructor return type (which is similar to the on-type of a regular extension).
The question raised in this issue is whether we should allow the actual type arguments to enable resolution of an instance creation, or we should report a compile-time error as soon as we have detected that there are multiple declarations of constructors with the desired name. Here is an example:
class MyClass<X> {
final X x;
MyClass.inClass(this.x);
}
static extension E1<X extends num> on MyClass<X> {
factory MyClass.inExtension(X x) => MyClass.inClass(x);
}
static extension E2 on MyClass<int> {
factory MyClass.inExtension(int i) => MyClass.inClass(i);
}
void main() {
// Currently specified rule.
MyClass<int>.inExtension(14); // Error, ambiguous: `E1<int>` and `E2` has it.
MyClass<num>.inExtension(14); // OK, only `E1<num>` has it.
}
A proposal has been made to make this an error even in the second case because both E1
and E2
have the on-class MyClass
, and both of them provide a constructor named MyClass.inExtension
.
According to the proposal in #3835, it is not an error, because only E1
is capable of receiving type arguments such that its constructor return type is the specified type MyClass<num>
(namely: E1<num>
).
So @dart-lang/language-team, do you prefer to report an error early (by declaring an ambiguity based on the on-class alone), or do you prefer to take the type parameters into account, and only report an error if there is an ambiguity among the static extensions that are able to match the requested type?
Edit: Corrected the constructor names in the instance creations in main.