Python Generics: Type Parameters, Bounds & Methods
Generics (`<T>`) allow you to write reusable classes, interfaces, and methods that work with any type while preserving compile-time type safety. Unlike Java (which uses type erasure), Dart's generics are **reified**, meaning type arguments are preserved at runtime (`list is List<String>` evaluates accurately). Generic type bounds (`<T extends Comparable<T>>`) restrict allowed types.
"Generics are like customizable shipping crates: the crate's physical shape and handles work universally, but a label `<FragileGlass>` specifies exactly what type of cargo is safe to pack inside."
Deep Dive: How It Works
Reified Generics: Runtime type information is preserved (`<int>[] is List<int>` is `true`).
Generic Type Bounds: `class Repository<T extends Model>` ensures `T` inherits model capabilities.
Generic Methods: `T firstOrFallback<T>(List<T> items, T fallback)` provides polymorphic utility functions.
Syntax Blueprint
// Generic Stack Class
class Stack<T> {
final List<T> _items = [];
void push(T item) => _items.add(item);
T pop() => _items.removeLast();
}Generic class declaration parameterized by type T.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Using raw generic types (`List` instead of `List<String>`).Why it happens: Legacy code habits.
How to fix: Always specify explicit type arguments to maintain Sound Null Safety and type inference.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Generic Pair Structure
Create a generic class `class Pair<A, B> { final A first; final B second; Pair(this.first, this.second); }`.
In `main()`, instantiate `final pair = Pair<String, int>("Code", 101);`.
Print `Pair: ${pair.first} -> ${pair.second}`.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.