Error with: Map<K,V> inside class Container<K,V>

52 views
Skip to first unread message

Julio Otuyama

unread,
Feb 19, 2015, 8:32:42 AM2/19/15
to haxe...@googlegroups.com
Hello,
I am trying to create a Container class with a Map with generics. This is the code:

class Container<K,V> {
var m:Map<K,V>;
public function new() {
m = new Map<K,V>();
}
}
 
But it gives the error:

  Abstract Map has no @:to function that accepts IMap<Container.K, Container.V>

There is this thread, but I am new to Haxe, so I dont know how to fix the code:


Thanks,
Julio

Simon Krajewski

unread,
Feb 19, 2015, 8:42:43 AM2/19/15
to haxe...@googlegroups.com
I really need a FAQ for this question. :) The problem is that Map has to select a concrete implementation at compile-time depending on its key type. The implementations are quit different for e.g. Int keys and object keys and there is no form of dynamic map which accepts any kind of key.

For a class like your Container<K, V> the key type K could potentially be anything so the compiler does not know which Map implementation to pick. There are two approaches here:

1. Constrain your key type to something, e.g. `class Container<K:{}, V>`. This way the compiler knows that it's supposed to pick ObjectMap.
2. Make your class @:generic and also add the @:remove metadata. This way the compiler makes concrete classes for your types (e.g. Container_String_Int) and then knows which Map type to pick. The @:remove metadata tells it that the generic base class itself (Container) should not be part of the output. Without it you would still get the error for it.

Simon

Sven Bergström

unread,
Feb 19, 2015, 9:32:24 AM2/19/15
to haxe...@googlegroups.com
Wow I have wrestled with this a couple of times. 
I think a note in the manual is crucial, because a map of a type parameters is quite common!
I've even resorted to forcing a map time directly at times to ObjectMap when the key could be an Int  ...

Julio Otuyama

unread,
Feb 20, 2015, 8:42:20 AM2/20/15
to haxe...@googlegroups.com
Hello Simon,
The first approach worked fine, but it does not work with Int, is that correct?
The second approach is a little bit harder to understand. Is there some link with sample code for @:remove metadata?
Thanks for the answer.
Julio.

Simon Krajewski

unread,
Feb 20, 2015, 10:40:43 AM2/20/15
to haxe...@googlegroups.com
Am 20.02.2015 um 14:42 schrieb Julio Otuyama:
> Hello Simon,
> The first approach worked fine, but it does not work with Int, is that
> correct?
> The second approach is a little bit harder to understand. Is there
> some link with sample code for @:remove metadata?
> Thanks for the answer.

Just try

@:remove
@:generic
class Container<K, V> { // etc.


Simon

Julio Otuyama

unread,
Feb 20, 2015, 12:59:42 PM2/20/15
to haxe...@googlegroups.com
Thanks.
Reply all
Reply to author
Forward
0 new messages