Generic Classes

In this lesson, you will learn to use generic classes.

Generic Classes

Generic classes help restrict the type of values accepted by the class. These supplied values are known as the generic parameter(s).

In the following example, the class FreshProduce is restricted to accept only the Product data type. It is acceptable to use FreshProduce without the <Product> parameter as Dart will assume it to be of the type Product. However, if any other data type other than the allowed type is passed, you’ll see a compile-time error.

The FreshProduce Class

The FreshProduce class is restricting the type of values that can be supplied to the class. It can only accept input of Product type when T extends the Product class. The Product class is borrowed from previous lessons on generics.

class FreshProduce<T extends Product> {
  FreshProduce(int i, double d, String s);

  String toString() {
    return "Instance of Type: ${T}";
  }
}

Passing the Product type

The FreshProduce class only accepts the Product type. Let’s create an instance spinach of FreshProduce. As a result, an instance of type Product is created.

void main() {
  //Using `Product` parameter accepted by FreshProduce class
  FreshProduce<Product> spinach = FreshProduce<Product>(3, 3.99, "Spinach");
  print(spinach.toString());
}

Output:

Instance of Type: Product

Not Passing Product Type

When Product is not passed to the FreshProduce, it assumes that the data is of Product type.

void main() {
  //Passing no 
  FreshProduce spinach2 = FreshProduce(3, 3.99, "Spinach");
  print(spinach2.toString());
}

Output:

Instance of Type: Product

Passing any other type

The FreshProduce class cannot accept other data types. In the example below a compilation error is thrown when we try to pass an Object to it.

void main() {
   //This code will give compile time error complaining that Object is not of type Product
  FreshProduce<Object> spinach3 = FreshProduce<Object>(3, 3.99, "Spinach");
  print(spinach3.toString());
}

Output:

main.dart:34:35: Error: Type argument 'Object' doesn't conform to the bound 'Product' of the type variable 'T' on 'FreshProduce'.
 - 'Object' is from 'dart:core'.
 - 'Product' is from 'main.dart'.
Try changing type arguments so that they conform to the bounds.
  FreshProduce<Object> spinach3 = FreshProduce<Object>(3, 3.99, "Spinach");
                                  ^
main.dart:16:20: Context: This is the type variable whose bound isn't conformed to.
class FreshProduce<T extends Product> {

Get hands-on with 1400+ tech skills courses.