I wanted to post something codey again, and this is a topic that can confuse some, so here we go. This is actually a fairly broad topic, so I’m just going to cover some important things.
1. What is casting?
Casting is basically converting an object that is one type to another type.
2. Why do it?
There are numerous reasons – you’ll see them in the examples. One main reason is that you have to sometimes.
3. How do you do it?
Good, on to the real meat. There are to ways to explicitly cast (where you state it in your code) in ActionScript 3. The first one is by Type(myObject) .
var mySprite:Sprite = Sprite(randObject);
This takes a value of Type Number (5.5) and changes it to an integer, which is stored as myInt.
The second way is with the as operator: (myObject as Type)
var mySprite:Sprite = (randObject as Sprite);
This converts randObject to a Sprite.
4. So what are the differences in the two ways?
Here’s the major difference between the two methods. If Type(obj) fails because obj can’t be converted to Type, flash will throw an error. If (obj as Type) doesn’t work, flash will return null.
var arr:Array = new Array(); var sp2:Sprite = (arr as Sprite); trace(sp2); var sp1:Sprite = Sprite(arr);
This outputs null from line three since arr wasn’t a Sprite, and then throws an error in line 4 for the same reason.
5. You said you’d show me some uses!
//Say you have addChild(new Sprite()); //You want this stored in a variable, // but addChild returns a DisplayObject not a Sprite //Do this: var mySprite:Shape = (addChild(new Sprite()) as Sprite);
Or say you’re getting a Shape from an array, but the lack of code-completion in FlashDevelop is bothering you:
arr. //No! Where's my code-completion? //Do this: (arr as Shape).graphics.beginFill(0xFF0000,.8); //Yay! Completion!
//Or, with Math.random() var myIntfrom0to9:int=int(Math.random()*10); //Warning! int() truncates numbers, and is different than Math.floor()
//Convert Number to int trace(int(5.5)); //Outputs 5 //Warning! Don't use as when casting numbers trace(5.5 as int); //Outputs null since 5.5 isn't an int
6. You lied! int() is a global function!
Well, uh, yeah, but it’s still like casting. Actually, all the primitive (or global if you prefer) types have a method like this, it just adds a little functionality.