🎓 A1Learner
🔍
0 of 37 lessons completed

Dart Generic Methods

A generic method carries its own type parameter, written in angle brackets after the method name. The method then works for any element type the caller chooses.

A fallback for an empty list

firstOr returns the first element of a list. An empty list returns the fallback instead.

T firstOr<T>(List<T> items, T fallback) {
  if (items.isEmpty) {
    return fallback;
  }
  return items[0];
}

void main() {
  print(firstOr(<String>[], 'kiwi'));
  print(firstOr([4, 9], 0));
}

Two type parameters

pair carries a key type K and a value type V. One call can pair a String key with an int value.

String pair<K, V>(K key, V value) {
  return '$key : $value';
}

void main() {
  print(pair('Ada', 10));
  print(pair('Bob', 20));
}

A generic method in a plain class

Picker itself is not generic. Its last method carries the type parameter on its own.

class Picker {
  T last<T>(List<T> items) {
    return items[items.length - 1];
  }
}

void main() {
  var picker = Picker();
  print('last: ${picker.last(['a', 'b', 'c'])}');
  print('last: ${picker.last([10, 20, 30])}');
}

Inference at the call site

The call site writes no type argument. The compiler reads the type from the list it receives.

T firstOr<T>(List<T> items, T fallback) {
  if (items.isEmpty) {
    return fallback;
  }
  return items[0];
}

void main() {
  print(firstOr(['a', 'b'], 'z'));
  print(firstOr([1, 2], 0));
}

Example

T firstOr<T>(List<T> items, T fallback) {
  if (items.isEmpty) {
    return fallback;
  }
  return items[0];
}

void main() {
  var scores = <int>[];
  print('first: ${firstOr(scores, -1)}');
  scores.add(42);
  print('first: ${firstOr(scores, -1)}');
}

Key points

  • A generic function writes its type parameter before the return type, as in T firstOr<T>(List<T> items, T fallback).
  • The type parameter stands for one real type that the call site picks.
  • The compiler infers the type from the arguments, so most calls write no type at all.
  • A function can carry two type parameters and relate them, such as a key type and a value type.
  • A method inside a plain class can still be generic on its own.

In this example, firstOr runs on an empty list first and returns the fallback -1. The list then gains 42. The second call returns 42, the real first element.

Note

the fallback keeps an empty list safe without any null check.

Try it Yourself

Edit the code, then press Run.

Running is simulated · DartPad

Exercise

What does firstOr return when its list is empty?