Search code examples
classcastinghaxeimplicit

Can I define implicit cast behaviour for a class in Haxe?


Is it possible to define implicit casts for classes? For instance, I have a class Color:

class Color {
    public var r: Int;
    public var g: Int;
    public var b: Int;

    public function new(?r: Int = 0, ?g: Int = 0, ?b: Int = 0) {
        this.r = r;
        this.g = g;
        this.b = b;
    }
}

If I have a Array<Int> like this:

var myIntegerArray = [255, 0, 255]; // color written in RGB as an array
var c: Color = myIntegerArray; // <= how to make this possible?
trace(c.r);

I tried @:from on a static function in my class:

@:from
static public function fromArray(a: Array<Int>) {
    return new Color(a[0], a[1], a[2]);
}

but the compiler is still not happy about this (Error: Array<Int> should be Color).

I know I could just use the static function like var c = Color.fromArray(myIntegerArray); but I'm curious whether or not it is possible to implicitly cast it.


Solution

  • No, implicit cast for normal class is impossible. But you have three solutions:

    1. Create abstract Color(Array<Int>) instead class;

    2. Use "chain" e.g. class Color > abstract ColorAbs > Array<Int>;

    3. Use haxe.extern.EitherType<Color, Array<Int>>;

    I don't recommend the second solution.