It’s been few months I have been working on ActionScript and I was pretty disappointed by the fact that ActionScript does not support function overloading. I wonder why that is. Function overloading is what I have been using very often while working in Java and C#.
However, unavailability of constructor and method overloading does not handicap Actionscript 3. It is still powerful programming language enhanced architecturally and conceptually compared to previous version.There are two workarounds I have known so far for the unavailability of function overloading in ActionScript3.
- Using default parameters which will allow to call function with different number of parameters
- Using …..(rest) parameter i.e. ellipses followed by the name
The first one is pretty easy. The function should contain all the required parameters with default value associated with the parameters. For example:
public function foo(param1:int = 0, param2:int = 0, param3:int = 0):void{//do something
}
foo(2); //only param1 is provided. param2 and param3 will take the default value
foo(4,5); //param3 will take the default value
The second solution is to use rest parameter. The rest parameter is denoted by using ellipses followed by the name of the parameter as shown below:
public function foo(…..params):void{//do something
}
Using rest parameter allows a function to accept any number of comma delimited arguments which will be available to function in the form of array. For example:
foo( 2,3,4,5);All these arguments will be available to function as array such that first argument can be accessed using params[0] and so on.
The main issue with rest parameter is type safety. Using reset parameter means you will lose compile-time type safety.
Though there are few workarounds, I still prefer native method overload support which I hope will be introduced in future version.... link (1 Kommentar) ... comment