Reputation: 13196
I want a group of classes that are enum-like; we can't subclass enum, so a small class with one final int will do (const even better). I want the superclass to define some default behaviors, and let the subclasses override as needed. But that includes construction: I need a function or class generic on the super type to be able to create an instance of the subtype it's actually called on. For example (this doesn't work):
class A {
final int x;
A(this.x);
}
class B extends A {
B(this.x);
}
T newOne<T extends A>(int z) {
return T(z); // error
}
Dart doesn't allow that, so try a factory method:
class A {
final int x;
A(this.x);
factory newOne(int z) { return A(z); }
}
class B extends A {
B(this.x);
factory newOne(int z) { return B(z); }
}
T new one<T extends A>(int z) {
return T.newOne(z); // also doesn't work
}
Then Github copilot suggests I use a factory method variable:
typedef AFactory<T extends A> = T Function(int x);
class A {
final int x;
AFactory factory;
A(this.x): factory = A.newOne;
factory newOne(int z) { A(z); }
}
class B {
B(this.x): factory = B.newOne; // error
factory newOne(int z) { B(z); }
}
That tells me that "factory" is not a class member!
I've even tried the class A<T extends A>
thing that has worked
in the past to get ordinary (non-factory) methods to return a subtype
from methods defined in the super. But Dart won't let me do anything
with constructors or factories. This is doable in other languages.
Is there some magic technique or undocumented little corner of the language I'm missing?
Upvotes: 0
Views: 32