-
Notifications
You must be signed in to change notification settings - Fork 205
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Switching over generic runtime type does not work #1455
Comments
It's a delicate exercise to use That said, you can still make it work. The error occurs because you are trying to use You can in general use a function like class SubClassBase {}
class SubClass extends SubClassBase {}
class BaseClass {}
class Extension extends BaseClass {}
class GenericExtension<T extends SubClassBase> extends BaseClass {}
Type typeOf<X>() => X;
main() {
BaseClass c = GenericExtension<SubClass>();
var cRuntimeType = c.runtimeType;
if (cRuntimeType == Extension) {
print("Recognized: Extension");
} else if (cRuntimeType == typeOf<GenericExtension<SubClass>>()) {
print("Regocnized: GenericExtension<SubClass>");
} else if (c is GenericExtension) { // Use `is` to cover subtypes of `GenericExtension<dynamic>`.
print("Recognized: Unspecified Generic Extension");
} else {
print("Missed");
}
print('Runtime type is ${c.runtimeType}');
} The missing bit is that you cannot use a function invocation as a constant, which means that you cannot use a switch statement. You already need to use something other than switch because you need to use We're about to introduce a generalization of type aliases (that is, declarations starting with // Requires `--enable-experiment=nonfunction-type-aliases`
typedef GenericExtensionOfSubclass = GenericExtension<SubClass>;
class SubClassBase {}
class SubClass extends SubClassBase {}
class BaseClass {}
class Extension extends BaseClass {}
class GenericExtension<T extends SubClassBase> extends BaseClass {}
Type typeOf<X>() => X;
main() {
BaseClass c = GenericExtension<SubClass>();
var cRuntimeType = c.runtimeType;
switch (cRuntimeType) {
case Extension:
print("Recognized: Extension");
break;
case GenericExtensionOfSubclass:
print("Regocnized: GenericExtension<SubClass>");
break;
default:
if (c is GenericExtension) {
print("Recognized: Unspecified Generic Extension");
} else {
print("Missed");
}
}
print('Runtime type is ${c.runtimeType}');
} |
I'll close this issue as a duplicate of #123, where there is a request to allow parameterized type as an expression. |
Thank you for the detailed response. |
I have been using the
switch
statement to react to the specific implementation of an Object via itsruntimeType
.This does not work for Objects with a generic type parameter:
Output:
This is not a huge issue, since checking for the type with
is
works as expected.I was just wondering whether this is by design, since I had expected the switch version to work.
The text was updated successfully, but these errors were encountered: