How to make a function that accepts several types of parameters in ActionScript 3?

Can someone tell me how to make a function that works as shown below in ActionScript3.0?

function test(one:int){ trace(one);} function test(many:Vector<int>){ for each(var one:int in many){ test(one); } } 
+4
source share
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 rarely a good approach to using two sepaprate, clearly defined methods, because it can be difficult to say that the intent of these methods does not require a specific type.

I suggest a clearer set of methods, named accordingly, for example.

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

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

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

In the case of using Vector this should also work:

 function test(many:Vector.<*>):void { //now many can be Vector with any type. } 
+1
source

All Articles