[英]In Haxe, can you write a generic interface where a method type parameter is constrained by the class's type parameter?
I'm having trouble writing the generic interface below.我在编写下面的通用接口时遇到问题。
In my class, I have a function that takes an array of < any type that extends a parent class > and traces its first element.在我的 class 中,我有一个 function,它采用 < 扩展父 class 的任何类型 > 的数组并跟踪其第一个元素。 Since I'm only reading elements from the array, I'm using it as if its a covariant compound type , and therefore I'm guaranteed to have the cast statement never fail.
因为我只是从数组中读取元素,所以我使用它就好像它是协变复合类型一样,因此我保证 cast 语句永远不会失败。
Now I want to abstract this out even more and write a interface that defines fn using another generic type T. I want fn to be able to accept any Array < type that extends T >.现在我想进一步抽象它并编写一个使用另一个通用类型 T 定义 fn 的接口。我希望 fn 能够接受任何 Array < type that extends T >。 When I have my test class implement this interface, I get the compiler error: "Field fn has different type than in ConstraintInter".
当我的测试 class 实现这个接口时,我得到编译器错误:“Field fn has different type than in ConstraintInter”。 How can I correct this interface?
我怎样才能更正这个界面? Or is there some other method/work around to accomplish this?
或者是否有其他方法/解决方法来完成此操作?
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]);
}
}
You can using generic interface for that:您可以为此使用通用接口:
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斧头 4.1.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.