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.

Cequiel
  • 3,505
  • 6
  • 27
  • 44

1 Answers1

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);
}
Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
  • 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 '16 at 21:16
  • You are right. The code was a bit complex and I was a little confused. – Cequiel Jun 15 '16 at 15:40
  • This answer is the only place I have found on the whole of the internet that establishes that `BaseClass` syntax. Thanks so much @Alexandre Ardhuin - you put an end to my weekend of hair-pulling over mismatched generic types! – Craig Labenz Feb 04 '19 at 15:21