Why this generic classes throw errors? Since T extends DataModel
, it should allow to assign instances of DataModel
but isn't.
class TestClass<T extends DataModel> {
List<T> variablesList = [];
late T variable;
void run() {
variablesList.add(DataModel(id: '', name: '', value: '')); // error
variable = DataModel(id: '', name: '', value: ''); // error
}
void run2() {
variablesList.add(DateModelImpl(id: '', name: '', value: '')); // error
variable = DateModelImpl(id: '', name: '', value: ''); // error
}
}
class DataModel {
final String id;
final String name;
final String value;
DataModel({
required this.id,
required this.name,
required this.value,
});
}
class DateModelImpl extends DataModel {
DateModelImpl({
required String id,
required String name,
required String value,
}) : super(id: id, name: name, value: value);
}
Error:
The argument type 'DataModel' can't be assigned to the parameter type 'T'.
The argument type 'DateModelImpl' can't be assigned to the parameter type 'T'.
CodePudding user response:
Since T extends DataModel, it should allow to assign instances of DataModel but isn't.
No, it should not. It's pretty simple: A Pack<Wolf>
is something like Pack<T extends Animal>
, but that does not mean you can just add any animal to a pack of wolves, nor can you add any derived class of Animal that is not wolf
(lets say Sheep
) to a Pack<Wolf>
. Only another Wolf
can be added. If you want to be able to add any animal, maybe generics is not the way to go and you should rather use interfaces or base classes.