The following example of a factory constructor (using a static method) compiles fine:
class Base<T> {
Base();
static Base myFactory(bool isInt) {
if (isInt) { return A(); }
else { return B(); }
}
}
class A extends Base<int> {}
class B extends Base<String> {}
However, if I use the syntax for a factory constructor:
class Base<T> {
Base();
factory Base.myFactory(bool isInt) {
if (isInt) { return A(); }
else { return B(); }
}
}
class A extends Base<int> {}
class B extends Base<String> {}
I get:
A value of type 'A' can't be returned from the method 'myStatic' because it has a return type of 'Base<T>'.
Why is this an error? A
is a subtype of Base<int>
, so isn't it a subtype of the generic Base<T>
?
CodePudding user response:
If you don't specify a type, it is dynamic
by default. Thus, in the first case, the return type of the myFactory
method is Base<dynamic>
, while in the other case, the return type of Base.myFactory
method is Base<T>
.