Created
April 23, 2020 19:20
-
-
Save passsy/9c7b16d9dafd59fa115181985a1ba83d to your computer and use it in GitHub Desktop.
Type switch case
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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