Skip to content

Instantly share code, notes, and snippets.

@passsy
Created April 23, 2020 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save passsy/9c7b16d9dafd59fa115181985a1ba83d to your computer and use it in GitHub Desktop.
Save passsy/9c7b16d9dafd59fa115181985a1ba83d to your computer and use it in GitHub Desktop.
Type switch case
void main() {
final Object something = TypeA();
something.matchTypes({
TypeA : () => print("found A"),
TypeB : () => print("found B"),
});
}
extension Ext<ANY> on ANY {
void matchTypes<T>(Map<Object, void Function()> map) {
final key = map.keys.firstWhere((it) => it is T, orElse: () => null);
if(key == null) {
throw "No match found for type $T";
}
map[key].call();
}
}
class TypeA {
String name;
}
class TypeB {
String age;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment