Resolving nested type parameters

48 views
Skip to first unread message

Paul Harper

unread,
Jul 6, 2014, 1:53:29 AM7/6/14
to haxe...@googlegroups.com
Here is a simplified version of what I'm working with now.

class Model<T> {
   
public var attributes : T;
}

class Collection<M:Model<T>, T> {
   
public function toJSON() : Array<T>;
}

I would like to write the Collection class like this:

// Note I'm not specifying T as a type parameter of Collection, just Model
class Collection<M:Model<T>> {
   
public function toJSON() : Array<T>;
}

It doesn't seem that there is any way to get access to type parameter info on Model in the specification of Collection. The only way I can think of doing this is through a build macro, but that just seems like overkill.

The reason why the current setup annoys me can be illustrated like this:

var model = new Model<ModelAttributes>();
var collection = new Collection<Model<ModelAttributes>, ModelAttributes>();

It just seems clunky, and it's easy for line length to go long. Any ideas?

Luca

unread,
Jul 6, 2014, 5:36:54 AM7/6/14
to haxe...@googlegroups.com
You can always just rely on type inference and have simply:

var model = new Model();
var collection = new Collection();

:)

Max

unread,
Jul 7, 2014, 6:14:15 AM7/7/14
to haxe...@googlegroups.com
Unfortunately, type of the type parameter doesn't resolve to a new type parameter. Anyway, type parameters are limited, you can't access variables or methods if a parameter type is not constrained. So I would say, type parameters are necessary evil.

Since you are clearly constraining M to a Model, you might change code as follows:

class Collection<T> {
   
public var model:Model<T>;
   
public function new(m:Model<T>) { model = m; }
   
public function toJSON():Array<T> { return new Array<T>(); }
}

and then use it like this:

var model = new Model<ModelAttributes>();
var collection = new Collection<ModelAttributes>(model);
var array = collection.toJSON();


where collection constructor takes a model instance for a type safety check. The drawback in this way is that you are forced to use Model<T> instead of M all over your class.

Paul Harper

unread,
Jul 7, 2014, 11:40:42 AM7/7/14
to haxe...@googlegroups.com
That does seem like a pretty reasonable solution. I was also able to leverage type inference to reduce some code clunkiness. Thanks for the help!


--
To post to this group haxe...@googlegroups.com
http://groups.google.com/group/haxelang?hl=en
---
You received this message because you are subscribed to a topic in the Google Groups "Haxe" group.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages