[英]In Haxe, can you constrain a type parameter with a generic type in an interface?
[英]In Haxe, can you write a generic interface where a method type parameter is constrained by the class's type parameter?
我在编写下面的通用接口时遇到问题。
在我的 class 中,我有一个 function,它采用 < 扩展父 class 的任何类型 > 的数组并跟踪其第一个元素。 因为我只是从数组中读取元素,所以我使用它就好像它是协变复合类型一样,因此我保证 cast 语句永远不会失败。
现在我想进一步抽象它并编写一个使用另一个通用类型 T 定义 fn 的接口。我希望 fn 能够接受任何 Array < type that extends T >。 当我的测试 class 实现这个接口时,我得到编译器错误:“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]);
}
}
您可以为此使用通用接口:
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]);
}
}
斧头 4.1.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.