I just stumbled across a little type conversion quirk within Flex. I haven’t tested this in-depth, so I may yet be proven wrong.

However….check this out:

var someVal:string = “true”;
var bool:Boolean;
bool = someVal as Boolean; // bool == false;
bool = someVal; // bool == true;

If you try to explicitly cast a string to Boolean, the casting appears to fail silently, leaving the Boolean with its default value of false.

However, if you leave it to the runtime to convert, the conversion works fine.

Ya learn something new every day!

3 Comments

  1. Yes, ActionScript 3’s String-to-Boolean conversion does seem odd. Here is one way you can work around it:

    bool = (someVal == 'true') ? true : false;
    

    It’s a bit longer than “as Boolean”, but it should do the trick. You might want to use “===” as your comparison operator depending upon the situation.

  2. wow….just ran into this myself…. i thought ActionScript was a real language until i realized it couldn’t consistenly convert the string “true” to a boolean.

    ????

  3. I think your post is misleading. Unless things change with player version, here are the results I come up with:

    var booleanTest:Boolean = false;
    booleanTest = “true”;
    trace(“1: “+booleanTest); //1: true

    booleanTest = “false”;
    trace(“2: “+booleanTest); //2: true

    booleanTest = Boolean(“true”);
    trace(“3: “+booleanTest); //3: true

    booleanTest = Boolean(“false”);
    trace(“4: “+booleanTest); //4: true

    var stringTrue:String = “false”;
    booleanTest = stringTrue;
    trace(“5: “+booleanTest); //5: true

    stringTrue = “true”;
    booleanTest = stringTrue;
    trace(“6: “+booleanTest); //6: true

    stringTrue = “false”;
    booleanTest = stringTrue as Boolean;
    trace(“7: “+booleanTest); //7: false

    stringTrue = “true”;
    booleanTest = stringTrue as Boolean;
    trace(“8: “+booleanTest); //8: false


Post a Comment

*
*