Extension Types

Wrapped at compile time with zero additional runtime objects (zero-cost abstraction); used to assign a new set of static interfaces to existing types and restrict accessible methods.

Difference from regular Extensions: standard extensions add methods to every instance of the underlying type; an Extension Type only takes effect when the static type matches this extension type.

// int is the representation type, id refers to the underlying raw value
extension type IdNumber(int id) {
  operator <(IdNumber other) => id < other.id;
}Code language: Dart (dart)

Automatically generated members:

  1. Implicit constructor IdNumber(int id)
  2. Getter: int get id

Two Primary Modes (Most Widely Used)

1) Opaque Mode

Isolated interface|Recommended for business logic constraints

Omit the implements keyword

Hides methods from the underlying type to enforce interface limits

Direct assignment between the extension type and underlying type is disallowed

extension type IdNumber(int id) {
  operator <(IdNumber other) => id < other.id;
}

void main() {
  final id = IdNumber(100);
  id + 5;          // Compile error: no + operator, int addition is hidden
  final int raw = id; // Error, direct assignment not permitted
  final int raw = id as int; // Use explicit cast to retrieve raw value
}Code language: PHP (php)

2) Transparent Mode

implements representation-type

Inherits all members of the underlying type automatically; you may only add or override methods

extension type Num(int v) implements int {
  Num square() => Num(v * v);
}

void main() {
  final n = Num(5);
  print(n.isNegative); // Native int methods are directly accessible
}Code language: Dart (dart)

Constructor Usage Patterns

The positional parameter serves as the default constructor, which can be made private and hidden using ._

extension type Id._(int _raw) {
  // External code can only use this named constructor; direct Id(xxx) calls are blocked
  Id.create(int value) : _raw = value;
}Code language: JavaScript (javascript)

Supported constructs: methods, getters, setters, operators

Not allowed: instance variables, abstract members

Extension Types

Leave a Reply

Your email address will not be published. Required fields are marked *