在 Haxe 中,您可以在接口中使用泛型类型来约束类型参数吗?
In Haxe, can you constrain a type parameter with a generic type in an interface?
编辑:这个例子被简化了太多,我已经改写了这个问题here
下面我有一个人为的示例,其中我有一个通用接口,该接口带有一个方法,该方法接受 'extends' T 的 V 参数。然后我有一个 class 实现此接口,但是然后我无法获得与接口匹配的方法的类型。我如何让它编译?有没有另一种方法可以在不影响类型系统的情况下实现此功能?具体错误是"Field fn has different type than in ConstraintInter"。这是在 Haxe 4.0.5 上。
class TestParent { public function new() {} }
class TestChild extends TestParent { public function new() { super(); } }
interface ConstraintInter<T>
{
public function fn<V:T>(arg:V):Void;
}
class ConstraintTest implements ConstraintInter<TestParent>
{
public function new () {}
public function fn<V:TestParent>(arg:V):Void
{
trace(arg);
}
public function caller()
{
fn(new TestParent());
fn(new TestChild());
}
}
一些进一步的测试表明,我可以将类型参数与泛型类型限制在 class 本身内。添加接口出现这个错误。
也许你可以这样做:
class TestParent { public function new() {} }
class TestChild extends TestParent { public function new() { super(); } }
interface ConstraintInter<T>
{
function fn(arg:T):Void;
}
class ConstraintTest implements ConstraintInter<TestParent>
{
public function new () {}
public function fn(arg:TestParent):Void
{
trace(arg);
}
public function caller()
{
fn(new TestParent());
fn(new TestChild());
}
}
编辑:这个例子被简化了太多,我已经改写了这个问题here
下面我有一个人为的示例,其中我有一个通用接口,该接口带有一个方法,该方法接受 'extends' T 的 V 参数。然后我有一个 class 实现此接口,但是然后我无法获得与接口匹配的方法的类型。我如何让它编译?有没有另一种方法可以在不影响类型系统的情况下实现此功能?具体错误是"Field fn has different type than in ConstraintInter"。这是在 Haxe 4.0.5 上。
class TestParent { public function new() {} }
class TestChild extends TestParent { public function new() { super(); } }
interface ConstraintInter<T>
{
public function fn<V:T>(arg:V):Void;
}
class ConstraintTest implements ConstraintInter<TestParent>
{
public function new () {}
public function fn<V:TestParent>(arg:V):Void
{
trace(arg);
}
public function caller()
{
fn(new TestParent());
fn(new TestChild());
}
}
一些进一步的测试表明,我可以将类型参数与泛型类型限制在 class 本身内。添加接口出现这个错误。
也许你可以这样做:
class TestParent { public function new() {} }
class TestChild extends TestParent { public function new() { super(); } }
interface ConstraintInter<T>
{
function fn(arg:T):Void;
}
class ConstraintTest implements ConstraintInter<TestParent>
{
public function new () {}
public function fn(arg:TestParent):Void
{
trace(arg);
}
public function caller()
{
fn(new TestParent());
fn(new TestChild());
}
}