在Haxe中,您可以编写一个通用接口,其中方法类型参数受类的类型参数约束吗?

问题描述 投票:1回答:1

我在下面编写通用接口时遇到麻烦。

在我的类中,我有一个函数,该函数采用并跟踪其第一个元素。由于我只从数组中读取元素,因此我将其当作covariant compound type来使用,因此可以保证强制转换语句永远不会失败。

现在,我想进一步抽象出来,并编写一个使用另一个泛型T定义fn的接口。我希望fn能够接受任何扩展T>的Array

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个回答
0
投票

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

@:generic
interface ConstraintInter<T>
{
    // this causes a compiler error when implemented in class below
    public function fn<V:T>(arg:Array<V>):Void;
}
© www.soinside.com 2019 - 2024. All rights reserved.