2.4.5 Extensions

Extensions are used to express that a structure has all the fields of a given type as well as some additional fields of its own:

typedef IterableWithLength<T> = {
  > Iterable<T>,
  // read only property
  var length(default, null):Int;
}

class Main {
  static public function main() {
    var array = [1, 2, 3];
    var t:IterableWithLength<Int> = array;
  }
}

The greater-than operator > denotes that an extension of Iterable<T> is being created, with the additional class fields following. In this case, a read-only property length of type Int is required.

In order to be compatible with IterableWithLength<T>, a type must be compatible with Iterable<T> and provide a read-only length property of type Int. The previous example assigns an Array, which happens to fulfill these requirements.

since Haxe 3.1.0

Multiple structures can be extended at once:

typedef WithLength = {
  var length(default, null):Int;
}

typedef IterableWithLengthAndPush<T> = {
  > Iterable<T>,
  > WithLength,
  function push(a:T):Int;
}

class Main {
  static public function main() {
    var array = [1, 2, 3];
    var t:IterableWithLengthAndPush<Int> = array;
  }
}
since Haxe 4.0.0

An alternative notation for extension can be used, denoted by separating each extended structure with an & symbol.

typedef Point2D = {
  var x:Int;
  var y:Int;
}

typedef Point3D = Point2D & {z:Int};

class Main {
  static public function main() {
    var point:Point3D = {x: 5, y: 3, z: 1};
  }
}