00:00
00:00
Newgrounds Background Image Theme

cosoden just joined the crew!

We need you on the team, too.

Support Newgrounds and get tons of perks for just $2.99!

Create a Free Account and then..

Become a Supporter!

Haxe Generics: casting

648 Views | 1 Reply
New Topic Respond to this Topic

I'm having a hard time figuring out how to use Generics and casting instances to that type. Below is a test class with all of the errors commented next to the lines.

typedef TestClassSprite = TestClass<Sprite>;
class TestCast extends State {

	override public function create():Void {
		super.create();
		
		var foo:Dynamic = new TestClass<Sprite>("yup");
		
		// EXPECTING - true
		if (Std.is(foo, TestClass))// ERROR - Invalid number of type parameters for com.geokureli.testbed.misc.TestClass
			trace(cast(foo, TestClass).name);// ERROR - Invalid number of type parameters for com.geokureli.testbed.misc.TestClass
		
		// EXPECTING - true
		if (Std.is(foo, TestClass<DisplayObject>))// ERROR - Unexpected )
			trace(cast(foo, TestClass<DisplayObject>).name);// ERROR - Cast type parameters must be Dynamic
		
		// EXPECTING - true
		if (Std.is(foo, TestClass<Sprite>))// ERROR - Unexpected )
			trace(cast(foo, TestClass<Sprite>).name);// ERROR - Cast type parameters must be Dynamic
		
		// EXPECTING - true
		if (Std.is(foo, TestClassSprite))
			trace(cast(foo, TestClassSprite).name);// ERROR - Cast type parameters must be Dynamic
		
		// EXPECTING - false
		if (Std.is(foo, TestClass<MovieClip>))// ERROR - Unexpected )
			trace(cast(foo, TestClass<MovieClip>).name);// ERROR - Cast type parameters must be Dynamic
		
		// EXPECTING - true
		if (Std.is(foo, TestClass<Dynamic>))// ERROR - Unexpected )
			trace(cast(foo, TestClass<Dynamic>).name);
	}
}

class TestClass<T:DisplayObject> {
	
	public var name:String;
	
	public function new(name:String) { this.name = name; }
}

how do I use these? how do I upcast them?

EDIT: OMG When did newgrounds get an edit button!!!
P.S. sorry if this is the wrong forum, things have changed a bit around here.

Response to Haxe Generics: casting 2015-01-22 12:48:18 (edited 2015-01-22 12:49:16)


At 1/21/15 12:30 AM, GeoKureli wrote: how do I use these? how do I upcast them?

I've had plenty of problems with generic typecasting. Your first one should work because "Std.is(thing, Array)" works. You could try using a switch based off of Type.getClass().

It might be because of your T:DisplayObject bit, but it shouldn't care about that either way.