🎓 A1Learner
🔍
0 of 24 lessons completed

Dart Extension Types at Depth

An extension type can implement the type of its representation value. Implementing that type exposes the members of the representation through the extension type.

Implementing double

Celsius wraps a double and implements double. The round method of the double is callable on the Celsius value, and the is test passes.

extension type Celsius(double degrees) implements double {
  String get label => '${degrees.toStringAsFixed(1)} C';
}

void main() {
  var temp = Celsius(21.5);
  print(temp.label);
  print(temp.round());
  print(temp is double);
}

A const extension type in a const list

Meters is a const extension type over an int. Two of its values sit inside a const list, and each one still gives its label.

extension type const Meters(int value) {
  String get label => '$value m';
}

void main() {
  const spots = [Meters(3), Meters(4)];
  print(spots.length);
  print(spots[0].label);
  print(spots[1].label);
}

A generic extension type

Id takes a type parameter for the value it wraps. One Id holds an int and another holds a String, and the int pair compares equal by value.

extension type Id<T>(T value) {
  bool sameAs(Id<T> other) => value == other.value;
}

void main() {
  var a = Id<int>(7);
  var b = Id<int>(7);
  var name = Id<String>('ada');
  print(a.value);
  print(name.value);
  print(a.sameAs(b));
}

Example

extension type const Celsius(double degrees) implements double {
  String get label => '${degrees.toStringAsFixed(1)} C';
}

void main() {
  const temps = [Celsius(20.0), Celsius(21.5)];
  print(temps[0].label);
  print(temps[1].round());
  print(temps[1] is double);
}

Key points

  • Implementing the representation type exposes the interface of that type on the extension type.
  • A member of the representation, such as round on a double, becomes callable on the extension type value.
  • An extension type value that implements double passes an is double test, because the underlying value is a double.
  • A const extension type can appear in const collections, because its value is fixed at compile time.
  • A generic extension type takes a type parameter, so one shape can wrap an int, a String, or another type.
  • Erasure still applies, so at run time the value keeps the type of its representation.

In this example, Celsius is a const extension type that implements double, so its values sit in a const list. The first value prints its label, and the second value calls round from double and passes the is double test.

Try it Yourself

Edit the code, then press Run.

Running is simulated · DartPad

Exercise

What does implementing double give a Celsius extension type value?