【问题标题】:In Haxe, can you constrain a type parameter with a generic type in an interface?在 Haxe 中,您可以在接口中使用泛型类型来约束类型参数吗?
【发布时间】:2020-09-02 12:57:58
【问题描述】:

编辑:这个例子被归结为太多了,我已经改写了这个问题here

下面我有一个人为的例子,我有一个泛型接口,它带有一个接受“扩展”T 的 V 参数的方法。然后我有一个实现这个接口的类,但是我无法获得类型类型的方法来匹配接口。我如何让它编译?是否有另一种方法可以在不影响类型系统的情况下使其正常工作?具体错误是“Field fn has different type than in ConstraintInter”。这是在 Haxe 4.0.5 上。

class TestParent { public function new() {} }
class TestChild extends TestParent { public function new() { super(); } }

interface ConstraintInter<T>
{
    public function fn<V:T>(arg:V):Void;
}

class ConstraintTest implements ConstraintInter<TestParent>
{
    public function new () {}

    public function fn<V:TestParent>(arg:V):Void
    {
        trace(arg);
    }

    public function caller()
    {
        fn(new TestParent());
        fn(new TestChild());
    }
}

一些进一步的测试表明,我可以仅在类本身内使用泛型类型来约束类型参数。接口的添加使这个错误浮出水面。

【问题讨论】:

    标签: generics types interface haxe type-constraints


    【解决方案1】:

    也许你可以这样做:

    class TestParent { public function new() {} }
    class TestChild extends TestParent { public function new() { super(); } }
    
    interface ConstraintInter<T>
    {
        function fn(arg:T):Void;
    }
    
    class ConstraintTest implements ConstraintInter<TestParent>
    {
        public function new () {}
    
        public function fn(arg:TestParent):Void
        {
            trace(arg);
        }
    
        public function caller()
        {
            fn(new TestParent());
            fn(new TestChild());
        }
    }
    

    【讨论】:

    • 谢谢,这回答了我写的问题。不幸的是,我把原来的问题归结为太多了。我正在尝试编写一个处理covariant compound types 的接口。我发布了一个更好的问题here
    猜你喜欢
    • 1970-01-01
    • 2022-06-11
    • 2020-09-16
    • 2019-06-27
    • 2021-07-04
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多