Conversion to Primitive Types



When I first determined to datatype my codes strictly, I had this illusion that I must assign everything according to their data types. Here’s an example of me being disillusioned :P :

var age:uint = 2; // hardcoded value for testing
var isBorn:Boolean = ( age == 0 ) ? false : true;
trace( isBorn ); // returns true.
 
age = 0;
isBorn = ( age == 0 ) ? false : true;
trace( isBorn ); // returns false.

As you can see from the above example, it was not pretty. It was only when I read the section of Conversion to Primitive Types in Essential ActionScript 3.0 did it dispels my misconception. :D

So here’s what I can actually do:

var age:uint = 2;
var isBorn:Boolean = age;
trace( isBorn ); // returns true as well.
 
age = 0;
isBorn = age;
trace( isBorn ); // returns false. Works well!

In another typical scenario, if I wanted to make a movieclip’s visibility to false and alpha to 0, instead of doing:

mc.visible = false;
mc.alpha = 0;

I can just:

mc.visible = mc.alpha = 0;

** Do you see the advantage already? ** :)

More info about type conversions can be found here on Adobe LiveDocs.

The information below is referenced from: Essential ActionScript 3.0 by Colin Moock. Copyright 2007 O’Reilly Media, Inc., 0-596-52694-6
[Table=1][Table=2][Table=3][Table=4][Table=5]

AddThis Social Bookmark Button


2 Comments to “Conversion to Primitive Types”


rss Comments RSS
trackback Trackback
  1. Steven Sacks on April 3rd, 2008 at 12:09 am

    Instead of a ternary operation (a ? b : c), you can just say

    var flag:Boolean = (a == 0);

    or

    var flag:Boolean = (a == “hello”);

    This works really well for things like

    private function onButtonClick(e:Event):void
    {
    var i:int = buttons.length;
    while (i–)
    {
    e.currentTarget.selected = e.currentTarget == buttons[i];
    }
    }

  2. flashmech on April 3rd, 2008 at 12:15 pm

    I love that example! Thanks! :D

Leave a reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">