You can't use a normal cast...
var vertices = cast ([1, 2, 3, 4], Vector<Int>);
...because the type parameter has to be dynamic.
You can't use a generic cast...
var vertices:Vector<Int> = cast [1, 2, 3, 4];
... because these are separate types at runtime in Flash.
You can use Vector.ofArray...
var vertices = Vector.ofArray ([1, 2, 3, 4]);
...but now you can't use it with other NME targets.
NME uses a typedef to make nme.Vector<T> the same as Array<T>
You can't extend Array<T>...
class Vector<T> extends Array<T>
...because basic types (like Array) can't be extended
You can't create a new data type...
class Vector<T> implements ArrayAccess<T>
...because ArrayAccess<T> won't actually be supported on the target
platform for the new type
You can't add a "using" mix-in...
class VectorHelper {
static function ofArray (v:Vector<T>, a:Array<T>):Vector<T> {
return a;
}
}
...because this would work on vector instances, not the static Vector class
So how do we cleanly implement an API that requires the Vector type?
It would be wonderful to have a nice solution that doesn't require
conditional code, or some kind of VectorUtils class
class VectorHelper {
public static inline function ofArray (v:Class<Vector<T>>,
a:Array<T>):Vector<T> {
return cast a;
That was almost it. This works:
typedef Vector<T> = Array<T>;
class VectorHelper
{
public static inline function ofArray<T>(v:Class<Vector<Dynamic>>,
array:Array<T>):Vector<T>
{
return array;
}
}
This really helps.
Is there a way to implement this kind of functionality without requiring
"using nme.Vector"?
It would be great if this were added automatically when you imported the
nme.Vector class
I would actually reverse that and have "using" imply "import".
Simon
import using MyType;
would be nice.
That'd work for me as well, but unlike the direct implication this would
require a parser change. I'm not sure if the implication has a drawback
which would justify that. Either way is fine with me though.
Simon
There is a difference between the two in the native APIs and many other
places. For instance String.split returns an Array, while other API
methods uses Vectors. So we can't compile everything to either Array or
Vector.
BTW the AVM2 support for Vectors is not very good : they don't bring
that much speed improvement over Arrays and this they are not real generics.
Best,
Nicolas
@:native("Array") extern class Vector<T> implements
ArrayAccess<T> { ... }
The only drawback here is, that at runtime you have no way of figuring
out whether something was created as an Array or a Vector, but I think
that's ok.
Regards,
Juraj