Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a function that accepts multiple parameter types in ActionScript 3?

Can anyone tell me how to make a function that works like below in ActionScript3.0?

function test(one:int){ trace(one);}

function test(many:Vector<int>){
  for each(var one:int in many){ test(one); }
}
like image 561
Elonoa Avatar asked Feb 17 '23 09:02

Elonoa


2 Answers

You can use an asterisk and the is keyword:

function test(param:*):void
{
    if(param is int)
    {
        // Do stuff with single int.
        trace(param);
    }

    else if(param is Vector.<int>)
    {
        // Vector iteration stuff.
        for each(var i:int in param)
        {
            test(i);
        }
    }

    else
    {
        // May want to notify developers if they use the wrong types. 
        throw new ArgumentError("test() only accepts types int or Vector.<int>.");
    }
}

This is seldom a good approach over having two sepaprate, clearly labelled methods, because it can be hard to tell what that methods' intent is without a specific type requirement.

I suggest a more clear set of methods, named appropriately, e.g.

function testOne(param:int):void
function testMany(param:Vector.<int>):void 

Something that could be useful in this particular situation is the ...rest argument. This way, you could allow one or more ints, and also offer a little more readability for others (and yourself later on) to understand what the method does.

like image 200
Marty Avatar answered Feb 20 '23 00:02

Marty


function test(many:*):void {
  //now many can be any type.
}

In case of using Vector, this also should work:

function test(many:Vector.<*>):void {
  //now many can be Vector with any type.           
}
like image 30
sybear Avatar answered Feb 20 '23 00:02

sybear