【问题标题】:In Haxe, can you write a generic interface where a method type parameter is constrained by the class's type parameter?在 Haxe 中,您可以编写一个泛型接口,其中方法类型参数受类的类型参数约束吗?
【发布时间】:2020-05-16 18:45:25
【问题描述】:

我在编写下面的通用接口时遇到问题。

在我的类中,我有一个函数,它接受一个 的数组并跟踪它的第一个元素。因为我只是从数组中读取元素,所以我使用它就像它是一个covariant compound type,因此我保证强制转换语句永远不会失败。

现在我想进一步抽象它,并编写一个使用另一个泛型类型 T 定义 fn 的接口。我希望 fn 能够接受任何 Array 。当我让我的测试类实现这个接口时,我得到编译器错误:“Field fn has different type than in ConstraintInter”。如何更正此界面?还是有其他方法/解决方法来完成这个?

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

@:generic
interface ConstraintInter<T>
{
    // this causes a compiler error
    public function fn<V:T>(arg:Array<V>):Void;
}

@:generic
class ConstraintTest<T> implements ConstraintInter<T>
{
    public function new () {}

    public function fn<V:T>(arg:Array<V>):Void
    {
        var first:T = cast arg[0];
        trace(first);
    }

    public function caller()
    {
        var test = new ConstraintTest<TestParent>();
        // var test = new ConstraintTest();
        // Base case that always works
        test.fn([new TestParent()]);

        // I want this to work.
        var childArray:Array<TestChild> = [new TestChild()];
        test.fn(childArray);

        // This should throw a compile error.
        // test.fn([3]);
    }
}

【问题讨论】:

    标签: generics interface covariance haxe type-constraints


    【解决方案1】:

    您可以为此使用通用接口:

    class TestParent { public function new() {} }
    class TestChild extends TestParent { public function new() { super(); } }
    
    @:generic
    interface ConstraintInter<T>
    {
        // this causes a compiler error when implemented in class below
        public function fn<V:T>(arg:Array<V>):Void;
    }
    
    
    class ConstraintTest implements ConstraintInter<TestParent>
    {
        public function new () {}
    
        public function fn<V:TestParent>(arg:Array<V>):Void
        {
            var first:TestParent = cast arg[0];
            trace(first);
        }
    
        public function caller()
        {
            // Base case that always works
            fn([new TestParent()]);
    
            // I want this to work.
            var childArray:Array<TestChild> = [new TestChild()];
            fn(childArray);
    
            // This should throw a compile error.
            // fn([3]);
        }
    }
    

    Haxe 4.1.0

    【讨论】:

    • 这不起作用。我仍然遇到同样的编译器错误。
    • 如果您将函数注释为 ,则表示在 Class 声明中 T 与一个 不同 类型。
    猜你喜欢
    • 2020-09-02
    • 2022-06-11
    • 1970-01-01
    • 2020-09-16
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多