๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

Dart Generic Classes

A generic class declares a type parameter in angle brackets. The argument given at the use site decides that type for the whole object.

One class, two stored types

Box holds one value of the type named in its brackets. The peek method hands that value back with the same type.

class Box<T> {
  T contents;
  Box(this.contents);
  T peek() {
    return contents;
  }
}

void main() {
  var label = Box<String>('hello');
  var count = Box<int>(42);
  print(label.peek());
  print(count.peek());
}

Two type parameters

Pair declares two parameters, one for each field. The first slot takes a String and the second takes an int.

class Pair<A, B> {
  A first;
  B second;
  Pair(this.first, this.second);
}

void main() {
  var pair = Pair<String, int>('age', 30);
  print(pair.first);
  print(pair.second);
}

Inference from the constructor call

No type brackets appear at the use sites here. The compiler reads the argument types and fills the parameter in on its own.

class Box<T> {
  T contents;
  Box(this.contents);
}

void main() {
  var word = Box('dart');
  var number = Box(7);
  print(word.contents);
  print(number.contents);
  print(word.contents.runtimeType);
  print(number.contents.runtimeType);
}

Example

class Pair<A, B> {
  A first;
  B second;
  Pair(this.first, this.second);
  String describe() {
    return '$first = $second';
  }
}

void main() {
  var score = Pair('Ana', 10);
  print(score.describe());
  print(score.first);
  print(score.second);
}

Key points

  • A type parameter sits in angle brackets after the class name.
  • Inside the class, the parameter stands for the chosen type.
  • A Box of String stores a String, and a Box of int stores an int.
  • A class can declare two type parameters for two open slots.
  • The compiler infers the type arguments from the constructor arguments.
  • A method of a generic class can return the type named by the parameter.

In this example, the Pair is built from a String and an int, and the compiler infers both type arguments. The describe method joins the two stored values into one line.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

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