Skip to content

Instantly share code, notes, and snippets.

@craiglabenz
Created June 13, 2022 18:50
Show Gist options
  • Select an option

  • Save craiglabenz/3d0ff4dbd7a46072368f9248bd810725 to your computer and use it in GitHub Desktop.

Select an option

Save craiglabenz/3d0ff4dbd7a46072368f9248bd810725 to your computer and use it in GitHub Desktop.

Revisions

  1. craiglabenz created this gist Jun 13, 2022.
    28 changes: 28 additions & 0 deletions dart-enum-pattern-matching.dart
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    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'),
    );
    }