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

  1. Basic Creation

    • Definition: Comma-separated values in parentheses
    • Example:
      var point = (42, 3.14); // Inferred as (int, double)
  2. Type Annotations

    • Definition: Explicit record type signatures
    • Example:
      (int, String) getStatus() => (200, 'OK');
  3. 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

  1. Storage: Stack-allocated when possible
  2. Immutability: Fields cannot be modified
  3. 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.