Ted,

it seems like you have a wrong perception of what a type cast actually
is, not only in ActionScript, but in general.

A type cast is NOT about changing the type at runtime. if you write
something like this:

var o:Object = new ClassA();
var b:ClassB = ClassB(o);

this will actually *fail* (throw an error at runtime) unless ClassA
would be a subclass of ClassB. You cannot change the type at runtime.
There will definitly not be any constructor invocation or anything
similar. The purpose of casting is just:

At compile time: Tell the compiler what type you actually want to use.
Let's say you have ClassA which has a method doIt. If you type the
instance of ClassA as Object, the compiler will only allow you to use
properties and methods of Object. Because it does not know what the
runtime type will be. So if you would do this:

var o:Object = new ClassA();
o.doIt();

you'll get a compiler error, because Object does not have a doIt
method. If you then cast it back:

var a:ClassA = ClassA(o);
a.doIt();

the compiler won't complain. Casting is necessary because we have
compile time type checking.

The purpose at runtime: Just check if the cast you used was legal.
So a statement like ClassA(o) just means: pass the instance of o
through *unchanged* if it actually *is* already an instance of ClassA,
otherwise throw an error.

Now to add to the confusion: In ActionScript there are some
exceptions, where something that looks like a simple cast actually
*does* include invoking a function. This is the case for many top
level types like Array. If you write

    var a:Array = Array(o);

it will not be treated like a usual cast, it is a plain function call.
Which IMHO is very unfortunate and confusing. Other languages like
Java do not have these kind of special cases. So basically with the
old syntax you could not cast for these types, thus the new syntax

    var a:Array = o as Array

was introduced. There are only two differences between those two
options to cast: The new one (using "as") does not have these special
cases with the top level classes, so now you *can* actually do a
simple cast to Array. The second difference is how errors are treated
if the cast fails. The old syntax throws a runtime error, the new one
just returns null, if the cast fails (meaning you tried to trick the
compiler).

So really, casting is not about changing the type at runtime.


Jens




--
Flexcoders Mailing List
FAQ: http://groups.yahoo.com/group/flexcoders/files/flexcodersFAQ.txt
Search Archives: http://www.mail-archive.com/flexcoders%40yahoogroups.com 
Yahoo! Groups Links

<*> To visit your group on the web, go to:
    http://groups.yahoo.com/group/flexcoders/

<*> To unsubscribe from this group, send an email to:
    [EMAIL PROTECTED]

<*> Your use of Yahoo! Groups is subject to:
    http://docs.yahoo.com/info/terms/
 


Reply via email to