Skip to content

Instantly share code, notes, and snippets.

@craiglabenz
Created June 13, 2022 18:50
Show Gist options
  • Save craiglabenz/3d0ff4dbd7a46072368f9248bd810725 to your computer and use it in GitHub Desktop.
Save craiglabenz/3d0ff4dbd7a46072368f9248bd810725 to your computer and use it in GitHub Desktop.
Demonstrates pattern matching with Dart 2.17 enums
enum Key {
key1('key1'),
key2('key2');
final String value;
const Key(this.value);
T mapFor<T>({
required T Function() key1,
required T Function() key2,
}) {
if (value == Key.key1.value) {
return key1();
} else if (value == Key.key2.value) {
return key2();
}
throw Exception('Unexpected value for `value` of "$value" - did you forget to add a handler here?');
}
}
void main() {
Key key = Key.key1;
key.mapFor(
key1: () => print('This was key1'),
key2: () => print('This was key2'),
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment