如何解决Haxe中的“重复构造函数”错误?

Ene*_* F. 3 constructor haxe duplicates

在Haxe中,我创建了一个名为MyClass的类,如下所示:

class MyClass {

    var score: String;

    public function new (score: Int) {
        this.score = Std.string(score);
    }

    public function new (score: String) {
        this.score = score;
    }
 }
Run Code Online (Sandbox Code Playgroud)

我需要多个构造函数,但Haxe不允许我这样做。它从构建阶段抛出此错误:

*.hx:*: lines * : Duplicate constructor
The terminal process terminated with exit code: 1
Run Code Online (Sandbox Code Playgroud)

我怎么解决这个问题?

Gam*_*a11 6

这称为方法重载,Haxe除externs之外不支持(但将来可能会支持)。有多种方法可以解决此问题。

对于构造函数,通常的解决方法是为第二个构造函数使用静态的“工厂方法”:

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

您也可以有一个接受两种参数的构造函数:

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);   
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我不推荐这种方法,因为这种方法haxe.extern.EitherType本质上是Dynamic在后台进行的,这对类型安全性和性能不利。同样,EitherType从技术上讲,它仅适用于外部环境。

类型安全性更高,但也有些冗长的选项是haxe.ds.Either<String, Int>。在这里,您必须显式调用枚举构造函数:new MyClass(Left("100"))/ new MyClass(Right(100)),然后使用模式匹配来提取值。


支持从和进行隐式转换抽象类型,也可以选择:StringInt

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,还有一个实验库,它添加了对宏的重载支持,但是我不确定它是否支持构造函数。