Closed
Description
Problem
It seems generic type inheritance checking is not easy in Dart.
Solution one will have a long checking code when subtypes amount increased.
Solution two had more creation cost at the runtime.
Is it possible to provide a handy way of checking generic type inheritance?
Such as new keyword(maybe?):
T inherits Parent
Functions and Type Inheritance
void main() {
checkType<Child>();
}
class Parent {}
class Child extends Parent {}
void checkType<T extends Parent>() {
...
}
[==] check
print('[==] check can only check the exact type: ');
if (T == Parent) {
print('Tpye == Parent');
} else {
print('Tpye != Parent');
}
if (T == Child) {
print('Tpye == Child');
} else {
print('Tpye != Child');
}
[is] check
print('\n[is] check fail any tpye check: ');
if (T is Parent) {
print('Type is Parent');
} else {
print('Type is not Parent');
}
if (T is Child) {
print('Type is Child');
} else {
print('Type is not Child');
}
[switch] check
print('\n[switch] can only check the exact type: ');
switch (T) {
case Parent:
print('Type match case Parent');
break;
default:
print('Type is not matched case Parent');
}
switch (T) {
case Child:
print('Type match case Child');
break;
default:
print('Type is not matched case Child');
}
Solution one
if (T == Parent || T == Child) {
print('Type is either Parent or Child');
} else {
print('Type is neither Parent nor Child');
}
Solution two
if (<T>[] is List<Parent>) {
print('Type is either Parent or Child');
} else {
print('Type is neither Parent nor Child');
}
Results
[==] check can only check the exact type:
Tpye != Parent
Tpye == Child
[is] check fails any type check:
Type is not Parent
Type is not Child
[switch] can only check the exact type:
Type is not matching case Parent
Type match case Child
solution one:
Type is either Parent or Child
solution two:
Type is either Parent or Child