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.
No, implicit cast for normal class is impossible. But you have three solutions:
Create abstract Color(Array<Int>)
instead class
;
Use "chain" e.g. class Color
> abstract ColorAbs
> Array<Int>
;
Use haxe.extern.EitherType<Color, Array<Int>>
;
I don't recommend the second solution.