Record Decomposition
Record Decomposition
About
- Destructuring unpacks records into variables
- Works with both positional and named records
- Supports pattern ignoring with
_
- Enables concise value extraction
Main Topics
-
Positional Destructuring
- Definition: Matching positional patterns
- Example:
var (x, y) = (1, 2); print(x + y); // 3
-
Named Destructuring
- Definition: Binding by field names
- Example:
var (:name, :age) = (name: 'Alice', age: 30); print('$name is $age years old');
-
Ignoring Fields
- Definition: Skipping unwanted values
- Example:
var (_, y, _) = (1, 2, 3); // Only extract y
How to Use
- Multiple Returns: Immediately destructure
- Data Processing: Extract needed fields
- Pattern Matching: Combine with switches
How It Works
- Pattern Matching: Positional correspondence
- Type Checking: Ensures compatibility
- Scope: Creates new variables
Example:
(String, int, bool) getUserData() => ('Alice', 30, true);
void main() {
var (name, _, isActive) = getUserData();
if (isActive) print('$name is active');
}
Conclusion
Record decomposition provides an elegant way to extract and work with individual record fields, reducing boilerplate code while maintaining clarity. This feature shines when processing function return values or working with data transformations.