-
Notifications
You must be signed in to change notification settings - Fork 226
Description
It is currently a compile-time error for a redirecting factory constructor to specify a default value for a formal parameter (the idea is that we will always just use the ones that the redirectee has declared and hence it would be misleading to allow the default value to be specified):
class A {
A._([String message = "Hello, world!"]) {
print(message);
}
factory A([String message]) = A._;
}
class B {
B._([String message = "Hello, world!"]) {
print(message);
}
factory B([String message = "Got yer!"]) = B._; // Compile-time error!
}
This issue is a proposal to allow both A
and B
. This means that a redirecting factory constructor behaves like a forwarding function rather than a mere alias for the redirectee. Note that this is already true for a tear off (with factory C() = D;
, the reified return type of the torn-off C
constructor C.new
is C
and not D
).
Also, it should be a mere implementation detail that invocations of redirecting constructors can be inlined at compile time, so we shouldn't let that prevent redirecting factories from having their own default values (and, in general, being full-fledged functions, whenever needed).
Note that this would also allow developers to handle a typing conflict which has been discussed previously:
class E {
E._([num x = 3.14]);
factory E([int x]) = E._; // Specified to be an error.
}
The declaration of the constructor named E
is specified to be an error because the default value of x
isn't a type correct value for a parameter whose type is int
. There is no easy solution today (in particular, for a constant constructor), because the redirecting factory can't specify a different (and type correct) default value for x
, but with the proposal in this issue it could easily be specified, e.g., as int x = 3
.
The current behavior is actually to skip the issue (and not report any errors), but this means that developers can't inspect the constructor named E
and conclude that the actual argument for x
will always be an int
when an object is created using that constructor. Note that this situation could arise after the redirecting constructor has been written, because the redirectee could be updated to have a more general parameter type.
@dart-lang/language-team, WDYT?