HaxeFoundation / code-cookbook

The Haxe Code Cookbook - A community driven resource website for learning Haxe in practise
https://code.haxe.org
112 stars 87 forks source link

Generic instance method (@:genericInstance) #162

Closed joelmo closed 3 years ago

Simn commented 3 years ago

This is inaccurate (@:genericInstance does nothing here) and hacky (relying on naming schemes that might change) and thus not good content for the code cookbook.

joelmo commented 3 years ago

I mention that this is not a public feature and should be used with caution. Im fine with not having it in cookbook. But I think this is an interesting feature to explore. Sometimes you have a generic function that needs to handle some edge cases for certain type parameters. The other alternative is to use instanceof.

    static make_Bar(en,val) {
        return Type.createEnumIndex(en,val._hx_index,null);
    }
    static make_Foo(en,val) {
        console.log("Test.hx:16:","hello Foo");
        return Type.createEnumIndex(en,val._hx_index,null);
    }

        // compared to code generated using instanceof:
       static make(en,val) {
        if(js_Boot.__instanceof(en,Foo)) {
            console.log("Test.hx:12:","hello Foo");
            return Type.createEnumIndex(en,val._hx_index,null);
        } else {
            return Type.createEnumIndex(en,val._hx_index,null);
        }
    }
}

The code a little more efficient, we save some branches. In this case only one, but can be equal to the number of generic instances defined. Ideally, haxe would optimize type checks in generic methods. But right now this code is being generated:

    static make_Bar(en,val) {
        if(js_Boot.__instanceof(en,Foo)) {
            console.log("Test.hx:13:","hello Foo");
            return Type.createEnumIndex(en,val._hx_index,null);
        } else {
            return Type.createEnumIndex(en,val._hx_index,null);
        }
    }
    static make_Foo(en,val) {
        if(js_Boot.__instanceof(en,Foo)) {
            console.log("Test.hx:13:","hello Foo");
            return Type.createEnumIndex(en,val._hx_index,null);
        } else {
            return Type.createEnumIndex(en,val._hx_index,null);
        }
    }