Record Syntax
Record Syntax
About
- Positional Records bundle values without names
- Immutable by design with value semantics
- Type annotations are optional but recommended
- Perfect for temporary data grouping
Main Topics
-
Basic Creation
- Definition: Comma-separated values in parentheses
- Example:
var point = (42, 3.14); // Inferred as (int, double)
-
Type Annotations
- Definition: Explicit record type signatures
- Example:
(int, String) getStatus() => (200, 'OK');
-
Accessing Fields
- Definition: Positional field access
- Example:
var status = getStatus(); print(status.$1); // 200 print(status.$2); // 'OK'
How to Use
- Temporary Grouping: When you need to bundle a few values
- Multiple Returns: From functions/methods
- Data Transformation: Intermediate steps in pipelines
How It Works
- Storage: Stack-allocated when possible
- Immutability: Fields cannot be modified
- Type System: Treated as primitive types
Example:
(String, int) parseName(String input) {
return (input.split(' ').first, input.length);
}
void main() {
var (name, length) = parseName('John Doe');
print('$name ($length chars)');
}
Conclusion
Positional records provide a lightweight way to group related values without the overhead of class definitions. Their simple syntax and efficient implementation make them ideal for temporary data handling and multiple return scenarios.