Pattern Matching with Records

Pattern Matching with Records

About

  • Record Patterns work in switch and if-case statements
  • Enables declarative data extraction
  • Supports nested pattern matching
  • Compiler checks for exhaustiveness

Main Topics

  1. Switch Expressions

    • Definition: Pattern matching in switches
    • Example:
      String describe((num, String) pair) => switch(pair) {
        (>=0, var text) => 'Positive: $text',
        (_, 'special') => 'Special case',
        _ => 'Other'
      };
  2. If-Case Statements

    • Definition: Pattern matching in conditionals
    • Example:
      if (record case (int x, String s)) {
        print('Got $x and $s');
      }
  3. Nested Patterns

    • Definition: Matching nested records
    • Example:
      var record = (1, (2, 3));
      if (record case (int a, (int b, int c))) {
        print(a + b + c);
      }
  4. Guards

    • Definition: Additional conditions with when
    • Example:
      String check((int, String) r) => switch(r) {
        (var x, _) when x.isEven => 'Even',
        _ => 'Odd'
      };
  5. Exhaustiveness Checking

    • Definition: Compiler verifies all cases
    • Example:
      bool? getBool() => true;
      switch (getBool()) {
        case true: print('true');
        case false: print('false');
        // No null case needed if null-checked
      }

How to Use

  • Data Validation: Match expected shapes
  • State Handling: Different cases cleanly
  • API Responses: Process different result types
  • Transformations: Extract and convert data

How It Works

  1. Matching: Top-down pattern testing
  2. Binding: Variables capture matched values
  3. Types: Static checking of patterns
  4. Performance: Compiled to efficient jumps

Example:

String processResponse((int, Object) response) {
  return switch(response) {
    (200, String text) => 'Success: $text',
    (404, _) => 'Not found',
    (500, Exception e) => 'Error: ${e.toString()}',
    (_, _) => 'Unknown response'
  };
}

Conclusion

Pattern matching with records enables a declarative style of programming that makes complex data handling both readable and robust. By combining record destructuring with conditional logic, Dart programs can express sophisticated data processing flows with minimal boilerplate code.