![](/img/trans.png)
[英]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.