Description
As proposed in #3835, an extension (or static extension) declaration can have an 'on-class', and it is able to "inject" static members or constructors into its on-class, and not into any other declaration.
class A {}
static extension ExtendA on A {
A.name(int i): this();
static staticMethod() {}
}
void main() {
var a = A.name(3); // OK, same as `A()`.
A.staticMethod(); // OK.
ExtendA.staticMethod(); // Also OK.
}
The same approach would immediately be applicable to an enum, a mixin, a mixin class, and an extension type declaration. The mixin can't have a generative constructor, so we can't use a redirecting generative constructor in the extension, but that's just a normal error which is also applicable here.
I tend to prefer that we do not support the situation where the "on-class" is an extension or a static extension:
static extension E1 on String {}
static extension E2 on E1 { // Error.
static void foo() {}
}
The reason for this is that E2
might as well have String
as its on-class (calling the declarations of a static extension using the static extension itself as the syntactic receiver is expected to be a rare thing). That is, if someone wants to call E1.foo()
then they might just as well call String.foo()
(assuming we change E2
to have on-class String
) or E2.foo()
. Also, it doesn't make sense for E2
to inject any constructors into E1
, they should just be injected into String
in the first place.
@dart-lang/language-team, WDYT?