简体   繁体   中英

In Haxe, can you constrain a type parameter with a generic type in an interface?

EDIT: This example was boiled down too much, I've rephrased this question here

Below I have a contrived example where I have an generic interface with with a method that accepts an argument of V that 'extends' T. Then I have a class that implements this interface, but then I can't get type type of the method to match the interface. How do I get this to compile? Is there an alternative way to get make this functional without compromising on the type system? The specific error is "Field fn has different type than in ConstraintInter". This is on 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());
    }
}

Some further testing shows that I can constrain type params with generic types within just the class itself. The addition of the interface surfaced this error.

Maybe you can do this:

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());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM