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.
We can add generic type parameters to class methods, static methods, and interfaces. Generic classes can be extended to create subclasses of them, which are also generic.
Dart Generics are the same as the Dart collections, which are used to store the homogenous data. As we discussed in the Dart features, it is an optionally typed language. By default, Dart Collections are the heterogeneous type. In other words, a single Dart collection can hold the values of several data types.
T is the generic data type eg String, int or CustomModel etc. f is the function E is the new element returned by the function.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With