我在编写下面的通用接口(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/