Dart LanguageIntermediate30 XP4 min read
How do generics work in Dart, including bounded generics?
TL;DR: Dart generics use type parameters <T> for type-safe collections and classes. Bounded generics <T extends SomeClass> restrict T to a specific type or its subclasses.
Full Answer
Dart generics are reified — type information is preserved at runtime. Unlike Java's type erasure, List<int> and List<String> are distinct types at runtime in Dart.
🎯
Dart generics are covariant for classes and method return types — List<Cat> can be used where List<Animal> is expected. But this means runtime type errors are possible, unlike Java's stricter bounded wildcards.
Code Examples
dartGeneric class with bounded type parameter
Output
42 true 7 banana Result<int>
Interview Tip
💡
Dart's reified generics mean you can use T in is/as checks: if (x is T). This is impossible in Java due to type erasure. It enables powerful patterns like generic repositories and type-safe result types.
#generics#type-parameters#bounded#covariance