我在下面编写通用接口时遇到麻烦。
在我的类中,我有一个函数,该函数采用并跟踪其第一个元素。由于我只从数组中读取元素,因此我将其当作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]);
}
}
您可以为此使用通用接口:
@:generic
interface ConstraintInter<T>
{
// this causes a compiler error when implemented in class below
public function fn<V:T>(arg:Array<V>):Void;
}