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

Enes F.

在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;
    }
 }

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

*.hx:*: lines * : Duplicate constructor
The terminal process terminated with exit code: 1

我怎么解决这个问题?

Gama11

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

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

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)),然后使用模式匹配来提取值。


支持和进行隐式转换抽象类型也可以选择: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);
    }
}

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何解决此“无法解析构造函数”错误?

如何解决流程中的“无法在对象类型上调用构造函数”错误?

如何解决声纳静态代码分析错误“在C ++中明确定义缺少的副本构造函数,移动构造函数..”

如何解决Android中的重复类错误

如何解决“无参数构造函数”

重复进口报关错误如何解决?

如何解决重复符号错误?

如何解决 React Native 中的错误“cb 不是函数”?

在Java中访问对象函数时如何解决错误?

在R中运行cro函数时如何解决错误?

如何解决聚合SD函数中的错误消息?

如何解决“实体和Pojos必须具有可用的公共构造函数”错误?

如何解决错误“ ApplicationRole”不包含带有参数1的构造函数。[DbInitialize]?

如何解决“意外令牌:预期构造函数,方法,访问器或属性”错误?

如何解决“ Newtonsoft.Json.JsonSerializationException无法找到要用于类型的构造函数”的Android错误?

如何解决laravel中的重复输入

如何解决SQL中的重复值

NET Core中如何解决Web API构造函数中的依赖关系

如何解决聚合函数错误?

如何解决javascript“不是函数”错误

如何解决函数指针的错误?

我在构造函数中检测到valgrid的内存问题。我该如何解决?

我如何解决:在Jest中运行测试时,“ TypeError:wsModule.Server不是构造函数”

突变时,如何解决“ qq模型名称”不是graphql中的构造函数

我该如何解决打字稿错误“ x”没有初始化程序并且在构造函数中未明确分配?

Golang的“内部错误:重复加载”-如何解决此错误?

Dagger 2如何解决构造函数依赖

如何解决错误“此表达式不可构造”?

如何解决避免在vue中重复导航到当前位置的错误?