15

Is this the correct way to declare a "generic class" that extends another "generic class" in dart? Note that the generic parameter has a type restriction.

// available types
class BaseType {}
class DerivedType extends BaseType {}

class BaseClass<Type extends BaseType> {
  final Type prop;
  BaseClass(this.prop) {
    // can be either BaseType or DerivedType
    print(prop);
  }
}

class DerivedClass<Type extends BaseType> extends BaseClass<BaseType> {
  DerivedClass(BaseType prop) : super(prop);
}

The above code works, but I'm not sure if I am using the correct syntax.

1 Answer 1

24

Although your code is correct I think you made a semantic mistake in the generic of DerivedClass:

// available types
class BaseType {}
class DerivedType extends BaseType {}

class BaseClass<T extends BaseType> {
  final T prop;
  BaseClass(this.prop) {
    // can be either BaseType or DerivedType
    print(prop);
  }
}

class DerivedClass<T extends BaseType> extends BaseClass<T /*not BaseType*/> {
  DerivedClass(T /*not BaseType*/ prop) : super(prop);
}
3
  • That's what I though, but when I write your code I get a "Unsound implicit cast from BaseType to Type" warning.
    – Cequiel
    Jun 14, 2016 at 21:16
  • You are right. The code was a bit complex and I was a little confused.
    – Cequiel
    Jun 15, 2016 at 15:40
  • This answer is the only place I have found on the whole of the internet that establishes that BaseClass<T> syntax. Thanks so much @Alexandre Ardhuin - you put an end to my weekend of hair-pulling over mismatched generic types! Feb 4, 2019 at 15:21

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.