-
Notifications
You must be signed in to change notification settings - Fork 201
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 on bounded generic types #4085
Comments
You're switching on Then if Dart had the ability to recognize all the possible And in the current case, where the types are not generic, you haven't checked for So, unlikely to become a feature. |
Yep that makes sense 🙂 Could you explain what you mean by trusting type parameters "genetically"? Is there a 'proper' way to do something like class FromJsonObject {
static FromJsonObject fromJson(json) => ...;
}
class Subclass1 extends FromJsonObject {
static Subclass1 fromJson(json) => ...;
}
class Subclass2 extends FromJsonObject {
static Subclass2 fromJson(json) => ...;
}
// switch expression here is pseudocode
T fromJson<T extends FromJsonObject>(Map<String, dynamic> json) {
return switch(T) {
Subclass1 => Subclass1.fromJson(json),
Subclass2 => Subclass1.fromJson(json),
FromJsonObject => FromJsonObject.fromJson(json),
_ => throw UnimplementedError(),
}
} Essentially something like static inheritance - or maybe this would be considered the wrong way to go about such a thing? Typically I have this sort of thing pop up when constructing model classes from some serialised format, where the model classes inherit some (often sealed) base class. Thanks again for your help |
I mean "generically". Damn mobile keyboard autocorrect. |
No. You cannot go from type parameter, or the even less useful If you knew the actual static type at the point where you call |
This is where static interfaces would be useful. Rust just... does this. ie: |
It appears exhaustiveness checking isn't performed when switching on bounded generic types.
By adding a default case to this (which I don't can ever be called) the error goes away and this behaves as expected.
I may have missed the proper way to do this. If I had an object of type T then I understand I could use the usual exhaustiveness checking (Matching on B _ etc).
As an aside, matching const nullable types seems to require typedef'ing them, e.g.
Thanks for your help 🙂
The text was updated successfully, but these errors were encountered: