CodeBlanks Logo Icon CodeBlanks

Generic methods

Learn to define generic methods.

Generic methods

A method can also take its own type parameter. The type parameter is written before the return type, inside angle brackets.

Example: T first<T>(List<T> items) { return items[0]; }. Here the first method works on any list; it returns the first element. first<int>([1, 2, 3]) returns an int, first<String>(['a']) returns a String. The type parameter belongs to the method; the class does not need to be generic. This is the clean way to write type-safe helper methods.

Type inference at the call site

When calling a generic method you can write the type argument explicitly or let Dart infer it. first<int>([1, 2, 3]) is explicit; first([1, 2, 3]) is inferred.

During inference Dart looks at the argument type and decides T from it. Since [1, 2, 3] is a List<int>, T becomes int. The result is still type safe; the compiler catches wrong usage. Explicit writing shows the type to the reader at once; inference keeps the code short. Both forms give the same compile-time safety.

Practice Write and call a first<T> method

Define a generic method named T first<T>(List<T> items); its body should be return items[0];. In main, call it with var n = first<int>([10, 20, 30]); and print(n).

Starter code

main.dart
// Define the first<T> method

void main() {
  // Call first<int>([10, 20, 30]) and print
}

Sample solution

main.dart
// Define the first<T> method
T first<T>(List<T> items) {
  return items[0];
}

void main() {
  var n = first<int>([10, 20, 30]);
  print(n);
}

Expected output

10

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Add a type parameter to first

Question
T first____(List<T> items) {
  return items[0];
}
Answer
T first<T>(List<T> items) {
  return items[0];
}

Explanation: A generic method is written as T first<T>(List<T> items).

2 What does first<int>([10, 20, 30]) return?

  • The last element of the list
  • The length of the list
  • The first element of the list Correct answer
  • The whole list

Explanation: The first method returns the first element of the list.

3 Match the generic method parts

Term Meaning
T Return type
first Method name
List<T> Parameter type

All lessons in Intermediate