Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Covariant return type for subclasses

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>.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading