4

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); }
}
Elonoa
  • 467
  • 7
  • 19
  • Constructor overloading is not supported in AS3, however you can use the generic type parameter function test(foo:*):void{ – The_asMan Feb 26 '13 at 21:39

2 Answers2

7

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.

Marty
  • 39,033
  • 19
  • 93
  • 162
  • Thanks. Wanted to make my FlashDevelop parse the parameter type if it can but I'm going to make 2 functions for it. – Elonoa Feb 27 '13 at 02:20
  • @Elonoa Realistically you should do whatever works for you. If you are working on your own and you're confident that you can recall what your function does down the track then it's perfectly fine. If you work on many large projects and often have others jump in to make updates like me, then clarity is really important and you should probably have the separated methods. – Marty Feb 27 '13 at 02:45
  • Also if you're using FlashDevelop, here is an excellent place to make use of the code hinting using your own comments. – Marty Feb 27 '13 at 02:54
1
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.           
}
sybear
  • 7,837
  • 1
  • 22
  • 38