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); }
}
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.
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With