这称为方法重载,除了externs(但might be in the future)之外,Haxe 不支持这种方法。您可以通过多种方式解决此问题。
在构造函数的情况下,一个常见的解决方法是为第二个构造函数使用静态“工厂方法”:
class MyClass {
var score:String;
public function new(score:String) {
this.score = score;
}
public static function fromInt(score:Int):MyClass {
return new MyClass(Std.string(score));
}
}
你也可以有一个接受这两种参数的构造函数:
class MyClass {
var score:String;
public function new(score:haxe.extern.EitherType<String, Int>) {
// technically there's no need for an if-else in this particular case, since there's
// no harm in calling `Std.string()` on something that's already a string
if (Std.is(score, String)) {
this.score = score;
} else {
this.score = Std.string(score);
}
}
}
但是,我不推荐这种方法,haxe.extern.EitherType 本质上是 Dynamic,这不利于类型安全和性能。此外,EitherType 在技术上仅用于外部人员。
haxe.ds.Either<String, Int> 是一个更类型安全但也更冗长的选项。在这里,您必须显式调用枚举构造函数:new MyClass(Left("100")) / new MyClass(Right(100)),然后使用pattern matching 提取值。
从String 和Int 支持implicit conversions 的abstract type 也可能是一个选项:
class Test {
static function main() {
var s1:Score = "100";
var s2:Score = 100;
}
}
abstract Score(String) from String {
@:from static function fromInt(i:Int):Score {
return Std.string(i);
}
}
最后,还有an experimental library 增加了对宏的重载支持,但我不确定它是否支持构造函数。