trying out some edge cases with generics in static fields, I came over this Try Haxe!
import Type;
class Foo<T> {
static public var first: T;
static var isSet: Bool = false;
var val: T;
public function new(v: T) {
val = v;
if ( ! isSet) {
first = v;
isSet = true;
}
}
public function getFirst(): T {
return first;
}
}
class Test {
static function getName(vt: ValueType) {
return switch vt {
case TNull: "Null";
case TInt: "Int";
case TFloat: "Float";
case TBool: "Bool";
case TObject: "Object";
case TFunction: "Function";
case TClass(c): Type.getClassName(c);
case TEnum(e): Type.getEnumName(e);
case TUnknown: "unknown";
}
}
static function test<T>(v: T, vt: ValueType) {
final name = getName(vt);
if (Type.typeof(v) == vt)
trace('value is $name with value $v');
else
trace('oops value $v is not a $name');
}
static function main() {
trace("Haxe is great!");
var f1 = new Foo(1);
var e1 = f1.getFirst();
test(e1, TInt);
var f2 = new Foo("Bar");
var e2: String = f2.getFirst(); // get an Int but expect a String. Why does this compile ???
test(e2, TClass(Type.resolveClass("String"))); // I am expecting a String but get an Int
}
}
I am not using Dynamic but still can get the wrong type for e2 in this example. For me it is a bug.
My goal is not getting this to run, but to have a defined behaviour in my Haxe to nim target which am working on again - and I am having a hard time with generics in static fields
Cheers Adrian.