Dart: extends generic class with restrictions
Asked Answered
E

1

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.

Endoderm answered 14/6, 2016 at 20:38 Comment(0)
D
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);
}
Drobman answered 14/6, 2016 at 21:10 Comment(3)
That's what I though, but when I write your code I get a "Unsound implicit cast from BaseType to Type" warning.Endoderm
You are right. The code was a bit complex and I was a little confused.Endoderm
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!Intake

© 2022 - 2024 — McMap. All rights reserved.