Pattern Matching with Records
Pattern Matching with Records
About
- Record Patterns work in
switch
andif-case
statements - Enables declarative data extraction
- Supports nested pattern matching
- Compiler checks for exhaustiveness
Main Topics
-
Switch Expressions
- Definition: Pattern matching in switches
- Example:
String describe((num, String) pair) => switch(pair) { (>=0, var text) => 'Positive: $text', (_, 'special') => 'Special case', _ => 'Other' };
-
If-Case Statements
- Definition: Pattern matching in conditionals
- Example:
if (record case (int x, String s)) { print('Got $x and $s'); }
-
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); }
-
Guards
- Definition: Additional conditions with
when
- Example:
String check((int, String) r) => switch(r) { (var x, _) when x.isEven => 'Even', _ => 'Odd' };
- Definition: Additional conditions with
-
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
- Matching: Top-down pattern testing
- Binding: Variables capture matched values
- Types: Static checking of patterns
- 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.