Generic map factory syntax?

Hi! I try to create a simple factory method to create a map in a typed way but can’t figure out the correct method syntax. I created a simple example at Try Haxe ! :slight_smile:

class MapUtil {

    public static function createLazy<T,M>( existing : Map<T,M> ) : Map<T,M> {

        if ( existing == null ) existing = new Map<T,M>();
        return existing;
    }
}

class Test {
    static function main() {
        
        // Declare typed variable without value
        var mapIMightNeed : Map<String,Int> = null;
        
        mapIMightNeed = MapUtil.createLazy( mapIMightNeed );
        mapIMightNeed.set( "key", 1 );
    }
}

I tried several approaches. So maybe you know how it’s done? I rarely use generics and only with an single type…

You need to add @:generic to your createLazy function (see Generic - Haxe - The Cross-platform Toolkit).

Otherwise you’ll only have one T and M for all the calls to the function, and it won’t be able to create the correct map type.

Thanks a lot!

class MapUtil {

    @:generic
    public static function createLazy<K,V>( existing : Map<K,V> ) : Map<K,V> {

        if ( existing == null ) existing = new Map<K,V>();
        return existing;
    }
}

class Test {
    static function main() {
        
        // Declare typed variable without value
        var mapIMightNeed : Map<String,Int> = null;
        var mapIMightNeed2 : Map<Int,String> = null;
        
        mapIMightNeed = MapUtil.createLazy( mapIMightNeed );
        mapIMightNeed2 = MapUtil.createLazy( mapIMightNeed2 );
        
        mapIMightNeed.set( "key", 1 );
        mapIMightNeed2.set( 1, "value" );
    }
}