Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 61 ยท Collections

Generics

Learn Dart generics: generic classes and functions, type inference, bounds with extends, covariance and its runtime checks, and why Dart generics are reified.

You have been using generics since the first list: in List<int> the <int> is a type argument. Generics let one piece of code work with many types while the compiler still checks that you use them consistently. Without generics, a list would have to hold Object or dynamic, and you would cast every value you read. With them, List<String> promises that every element is a string.

This lesson shows how to write your own generic classes and functions, how to restrict the types allowed, and two Dart-specific points: generic types are covariant and they are reified, meaning they exist at runtime. The Dart code is read-only; TypeScript stand-ins let you run the matching ideas.

A generic class

Declare type parameters in angle brackets after the class name. By convention a single parameter is T (for "type"); collections often use E (element), and maps use K and V.

DART
class Box<T> {
  T value;
  Box(this.value);

  T get() => value;
  void replace(T newValue) => value = newValue;
}

void main() {
  var number = Box<int>(42);
  var text = Box('hello');            // T inferred as String

  number.replace(7);
  // number.replace('seven');         // compile error: String is not int
  print(number.get() + 1);            // 8, no cast needed
  print(text.get().toUpperCase());    // HELLO
}

Dart infers T from the constructor argument when it can, as in Box('hello'). When it cannot, spell it out: Box<int>(42), or give the variable a type (Box<num> b = Box(1); infers Box<num>).

A class can have several type parameters, and a generic class can be built on others:

DART
class Pair<A, B> {
  final A first;
  final B second;
  const Pair(this.first, this.second);

  Pair<B, A> swapped() => Pair(second, first);

  @override
  String toString() => '($first, $second)';
}

void main() {
  var p = Pair('age', 36);
  print(p);             // (age, 36)
  print(p.swapped());   // (36, age)
}
TypeScript A generic Box and Pair (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Generic functions and methods

Functions can have their own type parameters, written before the parameter list. The compiler infers them from the arguments:

DART
T firstOr<T>(List<T> items, T fallback) {
  return items.isEmpty ? fallback : items.first;
}

List<R> mapAll<T, R>(List<T> items, R Function(T) transform) {
  var result = <R>[];
  for (var item in items) {
    result.add(transform(item));
  }
  return result;
}

void main() {
  print(firstOr([3, 4], 0));            // 3
  print(firstOr(<String>[], 'none'));   // none
  print(mapAll([1, 2, 3], (n) => 'n$n')); // [n1, n2, n3]  (T=int, R=String)
}

Generic methods work the same way inside a class, which is how Iterable.map<R> and Future.then<R> are declared in the core library.

Bounds: limiting the allowed types

Inside Box<T>, T could be anything, so you can only do things every object can do. To call more specific methods, add an upper bound with extends:

DART
T largest<T extends Comparable<dynamic>>(List<T> items) {
  var best = items.first;
  for (var item in items) {
    if (item.compareTo(best) > 0) {
      best = item;
    }
  }
  return best;
}

double average<T extends num>(List<T> values) {
  var sum = 0.0;
  for (var v in values) {
    sum += v;     // allowed: T is known to be a num
  }
  return sum / values.length;
}

void main() {
  print(largest([3, 9, 4]));              // 9
  print(largest(['pear', 'apple']));      // pear
  print(average([1, 2, 3, 4]));           // 2.5
  // print(average(['a', 'b']));          // compile error: String is not a num
}

Without a bound the bound is Object?. A bound can be a class, an interface or another type parameter. The Comparable<dynamic> bound reads as "T has a compareTo method". We do not write Comparable<T> because int is a Comparable<num>, not a Comparable<int>, and the stricter bound would reject integer lists.

flowchart TD
    A["T extends Object?<br/>(no bound)"] --> B["T extends num"]
    B --> C["int"]
    B --> D["double"]
    A --> E["T extends Comparable"]
    E --> F["String, num, DateTime..."]

A bound narrows the types you may pass in, and in return widens what you can do with the value.

TypeScript Bounded generics (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Generics are covariant

In Dart, if Cat is a subtype of Animal, then List<Cat> is a subtype of List<Animal>. This is called covariance, and it makes code convenient: a function that accepts List<Animal> also accepts a List<Cat>.

DART
class Animal {}
class Cat extends Animal {}
class Dog extends Animal {}

void main() {
  List<Cat> cats = [Cat()];
  List<Animal> animals = cats;   // allowed: List<Cat> is a List<Animal>

  print(animals.length);         // 1: reading is always safe
  animals.add(Dog());            // compiles, but throws a TypeError at runtime!
}

The last line is the catch. The object is still a List<Cat>, and a dog cannot go in. Dart cannot reject the code at compile time without giving up covariance, so it inserts a runtime check on writes and throws a TypeError when the element has the wrong type. Reading is always safe; writing through a more general type is where the risk lives.

Two habits avoid surprises. First, do not widen a mutable list if you intend to add to it; create a new list (List<Animal>.of(cats), then add). Second, accept Iterable<Animal> instead of List<Animal> in functions that only read, because an iterable offers no way to add elements. You will also meet the covariant keyword, which lets an overriding method narrow a parameter type (see Inheritance and Polymorphism).

Generics are reified

Many languages (Java, TypeScript) erase type arguments after compiling, so at runtime a List<int> and a List<String> look alike. Dart keeps them. That means you can test and use type arguments at runtime:

DART
void main() {
  Object numbers = <int>[1, 2, 3];

  print(numbers is List<int>);       // true
  print(numbers is List<String>);    // false
  print(numbers.runtimeType);        // List<int>
}

Inside a generic class, T can appear in is T checks, in <T>[] literals and in T == int comparisons. That makes parsing and dependency-injection helpers easier to write than in languages with erasure, though comparing runtime types should stay the exception rather than the rule.

TypeScript Covariance and missing runtime types (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Generic type aliases and constraints on constructors

Type aliases can be generic too: typedef Json<T> = Map<String, T>;. And because generic classes are ordinary classes, they can extend each other: class NumberBox<T extends num> extends Box<T>. Abstract collections like Iterable<E>, List<E> and Map<K, V> are all generic classes you can extend or implement yourself, which is why custom collections can plug into the rest of the language.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the T in class Box<T> stand for?

    T is a placeholder. Box<int> and Box<String> are two different instantiations of the same class.
  2. 2. What does <T extends num> achieve?

    An upper bound limits the accepted types. In return, the code can use everything that num offers on values of type T.
  3. 3. What happens at runtime with List<Animal> a = <Cat>[]; a.add(Dog());?

    Generics are covariant, so the assignment compiles, but the list is really a List<Cat>. Dart checks writes at runtime and throws a TypeError.
  4. 4. What does it mean that Dart generics are reified?

    Reified means the type arguments are kept at runtime. A List<int> knows it is a List<int>, unlike languages that erase generics.
  5. 5. Which parameter type is safest for a function that only reads the elements?

    An Iterable<Animal> accepts a List<Cat> and offers no way to add elements, so the covariance risk disappears.

Summary

  • A type parameter like T makes a class or function work with many types while the compiler checks consistency.
  • Dart infers type arguments from values; spell them out for empty collections and when inference fails.
  • Bounds (T extends num, T extends Comparable<dynamic>) restrict the allowed types and unlock their members.
  • Generics are covariant: List<Cat> is a List<Animal>, and writes of the wrong type fail with a runtime TypeError.
  • Generics are reified: x is List<int> works and runtimeType shows the type arguments.
  • Prefer Iterable<T> parameters for read-only code.

Next, use everything so far to model real things in Classes and Objects.