user2765977
user2765977

Reputation: 499

Haxe: How can I setup a class to store data in an array of type that I pass in the constructor

I am coding in Haxe, Lime, OpenFl. I am trying to set up a Class to store data in a Map, referenced by class instance. The class type is to be passed in the constructor, via inference. But I am quite new to all this and can't quite figure out the syntax, this is what I got so far:

class DynamicStore<A>
{
    private var hashA:Map<Class<A>,String>;

    public function new<A>(paramA:Class<A>) {
        hashA = new Map();
    }
}

But this gives me the following error:

Abstract Map has no @:to function that accepts IMap<Class<DynamicStore.A>, String>

Is there a way to do this?

Upvotes: 0

Views: 301

Answers (2)

dagnelies
dagnelies

Reputation: 5321

A question first:

do you really want to use classes as key? or objects?

In classes should be the key

It would be much simpler to use the classe's full name as key, like "mypackage.blob.MyClass". It's safer, easier to handle and debug.

Map<String, String>

Would suffice in that case.

If objects should be keys

Then the code would look like:

import haxe.ds.ObjectMap;

class Test<A>
{
    static function main() {}

    private var hashA :ObjectMap<A,String>;

    public function new(paramA:A) {
        hashA = new ObjectMap<A,String>();
    }
}

The reason "Map" cannot be directly used in this case is that "Map" is a syntactic sugar, being resolved to StringMap, IntMap or others depending on the key type. If it doesn't know what kind of map to be used, it cannot proceed (this is mainly due to cross-compiling issues).

Remark

As a final note, I would mention your construction seems a bit wacky/strange to me. It would be interesting to know what you are trying to achieve and why you structure it the way you do.

Upvotes: 3

Franco Ponticelli
Franco Ponticelli

Reputation: 4440

I don't think you can use Class as the key of a Map. A good work around it to use a String as a key and the fully qualified names of the types. You can also define an abstract to move from the Type to String easily ... something like the following (code not-tested);

private var hashA : Map<String, String>;

public function addClass(className : ClassId, ...)

And the abstract will look something like this:

abstract ClassId(String) {
  inline public function new(name : String) this = name;
  @:from public static inline function fromClass(cls : Class<Dynamic>)
    return new ClassId(Type.getClassName(cls));
  @:to public inline function toClass() : Class<Dynamic>
    return Type.resolveClass(this);
  @:to public inline function toString() : String
    return this;
}

Upvotes: 2

Related Questions