Generic methods in Dart

Like Java, Dart also supports generic methods. Since a generic method performs intended actions on multiple kinds of data types, it removes the need to have various overloaded methods and promotes code reusability.

svg viewer

Dart supports the use of generic types (often denoted as T) in three general places:

  1. In a function’s arguments
  2. In local variables inside a function
  3. In a function’s return type

Code

Let’s look at an example where we want a generic function to return the item at the first index of a list of generic type T. The code below uses T in all three places we discussed above:

import 'dart:convert';
//This generic function prints and returns the item at the first index (0) of a list
T printFirst<T>(List<T> lst) { //List of generic type taken as function argument
T first = lst[0]; //Generic type as local variable
print(first);
return first; //Generic type as return value
}
void main() {
//Lists of three different data types declared
List<int> intList = [2, 4, 9, 10];
List<double> doubleList = [5.2, 9.1, 1.2, 3.5];
List<String> stringList = ["cat", "giraffe", "panther", "scorpion"];
//Generic function printFirst called on Lists if different times
printFirst(intList);
printFirst(doubleList);
printFirst(stringList);
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved