Beginner in Dart here.
abstract class Supertype {
WithQuantity<Supertype> newQuantity(num quantity) =>
WithQuantity(this, quantity)
}
class Subtype extends Supertype {
}
class WithQuantity<S extends Supertype> {
final S thing;
final num quantity;
WithQuantity(this.thing, this.quantity);
}
void main() {
WithQuantity<Subtype> quantityOfSubtype = Subtype().newQuantity(5);
}
I’d like for the last line to compile.
In this version of course it doesn’t, because newQuantity returns WithQuantity<Supertype>, not WithQuantity<Subtype>.
I can override the newQuantity method to make the return type narrower, but I’d have to do that for every subclass separately; seems duplicative.
In Java I could have done something like this:
class Supertype<S extends Supertype> {
WithQuantity<S> newQuantity(...);
}
But Dart doesn’t like this recursion.
Can I somehow tell the compiler that I need to return WithQuantity<whateverMyRuntimeTypeIs>?
Thanks!
>Solution :
You can declare Supertype as a generic whose type parameter is the subclass and then explicitly cast this to be that subclass type:
abstract class Supertype<S extends Supertype<S>> {
WithQuantity<S> newQuantity(num quantity) =>
WithQuantity(this as S, quantity);
}
class Subtype extends Supertype<Subtype> {}
class WithQuantity<S extends Supertype<S>> {
final S thing;
final num quantity;
WithQuantity(this.thing, this.quantity);
}
void main() {
WithQuantity<Subtype> listOfSubtype = Subtype().newQuantity(5);
}