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

标签 generics interface covariance haxe type-constraints

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

在我的类中,我有一个函数,它采用<扩展父类的任何类型>数组并跟踪其第一个元素。由于我只从数组中读取元素,因此我将其视为 covariant compound type ,因此我保证强制转换语句永远不会失败。

现在我想进一步抽象它并编写一个使用另一个泛型类型 T 定义 fn 的接口(interface)。我希望 fn 能够接受任何扩展 T 的 Array < type > 。当我让我的测试类实现此接口(interface)时,我收到编译器错误:“Field fn 的类型与 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]);
    }
}

最佳答案

您可以使用通用接口(interface):

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

关于generics - 在 Haxe 中,您可以编写一个通用接口(interface),其中方法类型参数受类的类型参数约束吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61841914/

相关文章:

python - 协方差矩阵的对角元素不是 1 pandas/numpy

java - eclipse 编译器或 javac ("type parameters of T cannot be determined"中的错误)

java - 为什么编译这个接口(interface)方法时会收到 "cannot find symbol"错误?

generics - Monodroid 泛型不是协变的?

c# - 回调接口(interface)合约

java - Java 有没有办法检查具体类是否实现具有相同完全限定名称的外部接口(interface)?

C# 类型转换错误尽管通用约束

c# - 将 struct 类型的通用列表绑定(bind)到 Repeater

Java 泛型返回类型

C# 泛型 : Can I constrain to a set of classes that don't implement an interface?