Sub topic 11
Generics
Generics let one class or function work with many types while the compiler still checks them. This chapter assumes you know Dart's classes, constructors, collections, and null safety from the earlier chapters. It also assumes you have seen List<int> and Map<String, int> before.
Why generics exist
Without generics, a container must either be written once per type or hold Object? and make every caller cast. Both options are bad. Generics add a type parameter, a placeholder such as T that the caller fills in. The compiler then checks every use against the real type.
You already use generics all the time:
List<String>is a list whose elements are all strings.Map<String, int>has two type parameters, one for keys and one for values.Future<int>completes with anint.
By convention, type parameters are single capital letters: T for a general type, E for an element, K and V for key and value, R for a return type.
Generic functions
Put the type parameter list right after the function name:
T firstOr<T>(List<T> items, T fallback) =>
items.isEmpty ? fallback : items.first;
void main() {
print(firstOr<String>([], 'none'));
print(firstOr([10, 20], 0));
}The first call passes the type argument explicitly. The second call leaves it out, and Dart infers T = int from the arguments. The function body treats T as an unknown type, so it can only use what every object supports (such as toString() and ==) unless you add a bound.
A function can have several type parameters, and they can appear in function types:
R apply<T, R>(T value, R Function(T) transform) => transform(value);
void main() {
final length = apply('Dart', (s) => s.length);
print(length);
}Here T is inferred as String from the first argument. Dart then infers the closure's parameter s as String, and R as int from the closure's result.
Generic classes
Put the type parameter after the class name. Inside the class, use T anywhere you would use a type:
class Stack<T> {
final List<T> _items = [];
bool get isEmpty => _items.isEmpty;
T? get peek => _items.isEmpty ? null : _items.last;
void push(T item) => _items.add(item);
T pop() {
if (_items.isEmpty) throw StateError('Stack is empty');
return _items.removeLast();
}
}
void main() {
final names = Stack<String>();
names.push('Ada');
names.push('Linus');
print(names.pop().toUpperCase());
print(names.peek);
// names.push(42); // compile-time error: int is not a String
}pop() returns a String, so you can call toUpperCase() with no cast. The commented line shows the point of generics: the compiler rejects the wrong type before the program runs.
Note that peek returns T?. If T is int, then T? is int?. A nullable type is built from the type parameter by adding ?.
Constructors and inference
When you create an instance, Dart infers type arguments from the constructor arguments or from the declared variable type:
class Pair<A, B> {
final A first;
final B second;
const Pair(this.first, this.second);
}
void main() {
final p = Pair('Ada', 36); // Pair<String, int>
final Pair<num, num> q = Pair(1, 2.5); // Pair<num, num> from context
print('${p.first} ${p.second} ${q.second}');
}You write Pair(...), not Pair<A, B>(...), for the constructor name. The type arguments go after the class name only when you spell them out: Pair<String, int>('Ada', 36).
flowchart TDDo not copy the line above. The real diagram follows.
Bounded type parameters
An unbounded T can be any type, so you can call almost nothing on it. A bound restricts T with extends, and in return lets the body use the bound's members:
class Box<T extends num> {
final T value;
Box(this.value);
double doubled() => value * 2.0;
}
T maxOf<T extends num>(T a, T b) => a > b ? a : b;
void main() {
print(Box(21).doubled());
print(maxOf(3, 7));
print(maxOf(2.5, 1.5));
// Box('hi'); // error: String does not extend num
}value * 2.0 compiles because T is known to be a num. Both int and double satisfy the bound.
If you omit a bound, the implicit bound is Object?. That means T may be nullable. Write T extends Object when you need a non-nullable type.
class Registry<T extends Object> {
final Map<String, T> _byName = {};
void add(String name, T item) => _byName[name] = item;
T? find(String name) => _byName[name];
}
void main() {
final r = Registry<int>();
r.add('answer', 42);
print(r.find('answer'));
print(r.find('missing'));
// Registry<int?>(); // error: int? does not extend Object
}Generics are kept at runtime
Dart generics are reified: the type arguments exist at runtime. This differs from Java, where they are erased after compilation.
void main() {
final ints = <int>[1, 2];
print(ints is List<int>);
print(ints is List<String>);
print(ints.runtimeType);
}This prints true, false, and List<int>. Because the type argument survives, you can write is List<int> checks and on clauses that depend on it.
Reification also explains a common surprise. An empty literal with no context has no information to infer from:
void main() {
var loose = []; // List<dynamic>
var typed = <int>[]; // List<int>
List<int> declared = []; // List<int>, inferred from the declared type
loose.add('anything');
typed.add(1);
declared.add(2);
print('$loose $typed $declared');
}dynamic turns off static checking for the elements. Always give an empty collection a type, either on the literal or on the variable.
Variance: generics are covariant
Dart treats generic types as covariant. If int is a subtype of num, then List<int> is a subtype of List<num>. This is convenient for reading but unsafe for writing:
void main() {
final ints = <int>[1, 2];
List<num> numbers = ints; // allowed
try {
numbers.add(3.5); // the real list holds only ints
} on TypeError {
print('runtime type error');
}
print(ints);
}The compiler accepts numbers.add(3.5) because 3.5 is a num. The list is really a List<int>, so Dart checks the argument at runtime and throws a TypeError. The output is runtime type error followed by [1, 2].
Generic type aliases and collections of generics
A typedef can take type parameters, which keeps long types readable:
typedef Json = Map<String, Object?>;
typedef Parser<T> = T Function(String input);
void main() {
final Parser<int> parseInt = int.parse;
final Json user = {'name': 'Ada', 'age': parseInt('36')};
print(user);
}Nested generics such as Map<String, List<int>> follow the same rules as simple ones. Type arguments nest freely, and inference works from the outside in.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Elements have type `dynamic` | Empty literal with no type or context | Write `<int>[]` or declare `List<int> xs = []` |
| `The argument type 'String' can't be assigned to 'int'` | Type argument fixed to `int` by the first argument or an explicit argument | Align the argument types, or widen with `<Object>` |
| `Type argument 'String' doesn't conform to the bound 'num'` | Argument does not satisfy `extends` | Use a type within the bound, or relax the bound |
| `TypeError` when adding to a list | Covariance: writing through a wider reference | Copy with `List<num>.from(...)` before writing |
| Cannot call a method on `T` | `T` has only the implicit bound `Object?` | Add `extends SomeType` |
| `T` accepts `null` unexpectedly | Implicit bound is `Object?` | Use `T extends Object` |
Design guidance
- Add a type parameter only when the types of several values in a signature must be related.
T firstOr<T>(List<T>, T)ties the list, the fallback, and the result together. A parameter used once, such asvoid log<T>(T x), gains nothing overObject?. - Prefer inference. Spell out type arguments when inference would give
dynamicorObject, or when it makes code clearer. - Choose the narrowest bound that supports what the body does.
Exercise
Given class Box<T extends num>, which of these fail to compile and why? (a) Box(5) (b) Box<String>('x') (c) Box<int?>(null)
Show answer
(a) compiles, with T inferred as int. (b) fails because String does not extend num. (c) fails because int? is nullable and num is not, so int? does not satisfy the bound.
Exercise
Write a generic function lastOr that returns the last element of a List<T>, or a fallback value of type T when the list is empty. Then say what type lastOr(<String>[], 'x') infers for T.
Show answer
T lastOr<T>(List<T> items, T fallback) => items.isEmpty ? fallback : items.last; The call infers T as String, because both the list and the fallback are strings.