Generics

Generics

About

  • Generics enable type-safe abstractions.
  • Parameterize classes and methods.
  • Reusable across different types.
  • Foundation of collection types.

Main Topics

  1. Generic Classes

    • Definition: Type parameters.
    • Example:
      class Box<T> {
        final T value;
        Box(this.value);
      }
  2. Generic Methods

    • Definition: Method-level type params.
    • Example:
      T first<T>(List<T> items) => items[0];
  3. Collection Types

    • Definition: Built-in generic collections.
    • Example:
      List<String> names = ['a', 'b'];
      Map<String, int> scores = {'a': 100};
  4. Bounded Types

    • **Definition`: Constraining type params.
    • Example:
      class NumberBox<T extends num> {...}

How to Use

  • Declare: Use angle brackets <T>
  • Constrain: extends for bounds
  • Instantiate: Provide concrete types
  • Infer: Let Dart deduce types

How It Works

  • Reification: Retains type at runtime
  • Safety: Prevents type errors
  • **Performance`: No boxing overhead

Example Session:

void main() {
  var box = Box<int>(42); // Explicit type
  var names = ['a', 'b']; // Inferred List<String>
}

Conclusion

Generics provide type-safe abstraction without sacrificing performance, enabling reusable code that maintains strict type checking throughout Dart applications.