Hello, not sure if this has come up before so I thought I'd file an issue! I'm implementing a Library and have found that I need two types of constructors: normal factory constructors for most parts, but I need static constructors when I need to work with generic parameters.
This leads to a slightly awkward API as constructors work like new MyClass.createSomething() methods, but others have to be MyClass.createSomething() without the new keyword indicating you're constructing a new object.
Perhaps it's easier to demonstrate with code, thanks for any info!
class MyClass<T> {
MyClass(T value);
factory MyClass.allGood(int a, int b, T combinerFn(int a, int b)) => new MyClass<T>(combinerFn(a, b));
// This is not valid, but I don't know why? I can't move from `a` and `b` being specified as `int` to `a` and `b` being specified with generic types.
factory MyClass.nope<A, B, T>(A a, B b, T combinerFn(A a, B b)) => new MyClass<T>(combinerFn(a, b));
// Making it a static constructor works, but means there are multiple ways to create `new` instances of this class
static MyClass<T> allGoodStatic<A, B, T>(A a, B b, T combinerFn(A a, B b)) => new MyClass<T>(combinerFn(a, b));
}
It has come up and it's on our radar.
When we added generic parameters to methods in Dart, we only added them to normal methods, not to constructors. Constructors kind-of-sort-of are generic because they can depend on the type parameter of the generic class, but as you have also realized, that's not always enough.
We plan to allow generic parameters on named constructors as well.
Unnamed constructors (like MyClass(...);) needs a little more thought so you won't be calling it as new MyClass<T><T2>() - that just doesn't look very readable.
Most helpful comment
It has come up and it's on our radar.
When we added generic parameters to methods in Dart, we only added them to normal methods, not to constructors. Constructors kind-of-sort-of are generic because they can depend on the type parameter of the generic class, but as you have also realized, that's not always enough.
We plan to allow generic parameters on named constructors as well.
Unnamed constructors (like
MyClass(...);) needs a little more thought so you won't be calling it asnew MyClass<T><T2>()- that just doesn't look very readable.