【发布时间】: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