Created
June 13, 2022 18:50
-
-
Save craiglabenz/3d0ff4dbd7a46072368f9248bd810725 to your computer and use it in GitHub Desktop.
Demonstrates pattern matching with Dart 2.17 enums
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
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