dart-lang / language

Design of the Dart language
Other
2.65k stars 202 forks source link

[Static Extensions] Can static extensions add constructors to mixins? #4050

Open leafpetersen opened 3 weeks ago

leafpetersen commented 3 weeks ago

Mixin declarations currently may not declare factory constructors:

mixin M {
  // This is an error
  factory M.foo() => throw "hello";
}

Both variants of the static extensions proposal in this PR imply that static extensions can be used to add factory constructors to mixin declarations (am I missing a restriction or error somewhere?). That is, the following would be legal:

mixin M {
}

extension on M {
  factory M.foo() => throw "hello";
}

Is this intentional? It seems slightly unfortunate that using an extension becomes "the way" to get a constructor onto a mixin. Should we relax this restriction on mixin declarations?

cc @dart-lang/language-team

natebosch commented 3 weeks ago

There is little practical difference between static M foo() => throw 'hello'; and factory M.foo() => throw 'hello';. Do we plan to allow a static extension to define the unnamed constructor? That's one affordance that might still only be open if we allow mixins to define factory constructors.

I don't see any harm in relaxing the existing restriction.

lrhn commented 3 weeks ago

Mixin declarations currently may not declare factory constructors

That's a long-standing missing feature. There was never any reason to disallow factory constructors on mixin declarations, and it should just be allowed.

We discussed that with class modifiers too, but to late in the process to want to add more to the feature.

So yes, relax the restriction. (Finally!)