haxe

Abstracts

Syntax#

  • abstract identifier(underyling type) { … }
  • abstract identifier(underlying type) from typeA from typeB … to typeA to typeB { … }

Remarks#

An abstract type is a compile-time type which resolves to the underlying type at run-time. This means that thee abstract type does not exist in the source code generated by the Haxe compiler. In its stead are placed the underlying type, or types defined for implicit casting.

Abstracts are denoted by the abstract keyword, followed by an identifier, and underlying type in parentheses.

Abstracts may only define method fields and non-physical property fields. Non-inlined method fields are declared as static functions in a private implementation class, accepting as an additional first argument the underlying type of the abstract.

Note that operator overloading is only possible for abstract types.

Abstracts for data validation

The following abstract defines an EmailAddress type based on the String type which will use a regular expression to validate the passed argument as an e-mail address. If the address isn’t valid, an exception will be thrown.

abstract EmailAddress(String) {
  static var ereg = ~/^[\w-\.]{2,}@[\w-\.]{2,}\.[a-z]{2,6}$/i;
  
  inline public function new(address:String) {
    if (!ereg.match(address)) throw "EmailAddress "$address" is invalid";
    this = address.toLowerCase();
  }
}

Use the abstract as follows.

var emailGood = new EmailAddress("john@doe.com");
var emailBad = new EmailAddress("john.doe.com");

Try the example on try.haxe.org.

References

Operator overloading

Operator overloading is only possible with abstract types.

The following abstract defines a Vec2i type based on the Array<Int> type. This is a two-component vector with integer values. Operator overloading is made possible my the @:op compiler metadata. Only the available numeric operators can be overloaded - custom operators are not allowed to be specified.

abstract Vec2i(Array<Int>) {
    public inline function getX() : Int {
        return this[0];
    }
    
    public inline function getY() : Int {
        return this[1];
    }
    
    public inline function new(x : Int, y : Int) {
        this = [x, y];
    }
    
    @:op(A + B)
    public inline function add(B : Vec2i) : Vec2i {
        return new Vec2i(
            getX() + B.getX(),
            getY() + B.getY()
        );
    }
}

Use the abstract as follows.

var v1 = new Vec2i(1, 2);
var v2 = new Vec2i(3, 4);
v1 + v2;
v1.add(v2);

Try the example on try.haxe.org.

References


This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow