bwroga
bwroga

Reputation: 5449

Can Vector be converted to a Boolean value?

I expected that if I passed a Vector to a method with a Boolean parameter, the compiler would complain. But it did not even give a warning. When I pass a Sprite as the parameter I get a warning, but the program still compiles. Why isn't the type checking system catching this?

package {
    import flash.display.Sprite;

    public class Main extends Sprite {
        public function Main():void {
            test(new Vector.<Number>()); // No warning or error.
            test(new Sprite()); // Warning, but no error.
        }

        public function test(value:Boolean):void {
        }
    }
}

Upvotes: 0

Views: 118

Answers (1)

Marty
Marty

Reputation: 39456

This is because your function test() will cast the value you give it to Boolean (true or false) depending on whether it is truthy or falsy.

Example:

function test(bool:Boolean):void
{
    trace(bool);
}

test( new Sprite() ); // true
test( 5 );            // true
test( undefined );    // false
test( "" );           // false
test( null );         // false

This is the same process used when preparing an if statement:

if(new Sprite())
{
    trace("Yep.");
}

if(null)
{
    // Never happens.
    trace("Nope.");
}

You can read more about the process of casting to Boolean here: Casting to Boolean.

Highlights

  • Casting to Boolean from an instance of the Object class returns false if the instance is null; otherwise, it returns true.
  • Casting to Boolean from a String value returns false if the string is either null or an empty string (""). Otherwise, it returns true.
  • Casting to Boolean from any of the numeric data types (uint, int, and Number) results in false if the numeric value is 0, and true otherwise. For the Number data type, the value NaN also results in false.

Upvotes: 4

Related Questions