Haxe Forum > Help with Type Parameter Constraint
-
Tom Byrne Aug 22 at 13:53
I'm having trouble getting the compiler to allow my to do something with type parameters.
I'm trying to map method calls to particular interface, the methods need to return classes which implement the specified interface.At the moment the simplified example below won't compile, saying:
Constraint check failure for registerType.MyKlassAny help would be greatly appreciated
package ; class TypingIssue { public function new() { registerType(ISpecific1, createClass1); registerType(ISpecific2, createClass2); } private function registerType < MyKlass : MyType, MyType : IGeneral > (type:Class<MyType>, creator:Void->MyKlass):Void { } private function createClass1():SpecificClass1 { return null; } private function createClass2():SpecificClass2 { return null; } } interface IGeneral { } interface ISpecific1 implements IGeneral{} interface ISpecific2 implements IGeneral{} interface SpecificClass1 implements ISpecific1{} interface SpecificClass2 implements ISpecific2{}
-
Can you post an example in your usual coding language, and I will try to forward it to an expert in that language, and/or can you explain the non abstracted problem and we can provide a solution and add theory later, but at the moment I could forward your question to the haxelang google group which is full of very advanced coders but I fear you would be ignored. Just ask the question in simple real terms and we can add any theory along the way, bear in mind that different languages often share theory but it may seem often to reside on a different conceptual plane and you maybe assuming the wrong approach for haxe.
-
Liburn Aug 26 at 10:52
Justin, did you try to compile example? You can't, unless you add missing part
class MyType implements IGeneral { }
And here is the problem: MyKlass should be MyType (SpecificClass1 should be registerType.MyType).
It is not possible to downcast IGeneral to MyType safely in this case, not in a zillion years.