Just write a Flex app and try the following in a function
var btn:Button = new Button();
var lst:List = new List();
lst = List (btn);
In short, we are trying to cast a button into a list… What do you expect?? Yes… an RTE (Run Time Error)
It reads
TypeError: Error #1034: Type Coercion failed: cannot convert mx.controls::Button@16ab0479 to mx.controls.List.
There are times in your app development cycle, when you are not sure, if a particular casting is allowed or not. You definitely don’t want to throw an RTE (Run Time Error) to the user either. What you end up doing invariably is using a try…catch block to handle the RTE. A better and cleaner alternative to this is using the as operator
Using the as operator has the following advantages
- It does the exact same thing as casting does, if you are casting between compatible types
- It returns a null if the object cannot be casted to a particular type
- No RTEs 🙂
Once you use the as operator, you can just do a null check to see if the casting is allowed… as below
var btn:Button = new Button;
var lst:List;
lst = btn as List;
if (! lst) {mx.controls.Alert.show(“Sorry you cant cast it this way”); }
But a word of caution. You cannot use the as operator to cast between types in the Top Level classes (to view them , go to the flex language reference). Which means… Say you want to cast a String to a Number, you cannot do,
num = str as Number;
This gives the following error
Implicit coercion of a value of type Number to an unrelated type String
You’ll have to do the age-old way of casting
num = Number(str);
Hope this is useful… at least to beginners 🙂