Variadic Functions in ActionScript

Here’s a function that will take an arbitrary number of int values as arguments.

public function sum(...nums:int):void {
    trace(nums, " ");
    var total:int = 0;

    for each (var num:int in nums) {
        total += num;
    }
    trace(total);
}

public function main():void {
    // Variadic functions can be called in the usual way with individual arguments.
    sum(1, 2);
    sum(1, 2, 3);

    // If you already have multiple args in an array, you can apply them to a variadic function using `apply`
    var nums:Array = [1, 2, 3, 4];
    sum.apply(null, nums);
}

To run the program and see the output.

$ amxmlc VariadicFunctions.as
$ adl VariadicFunctions.swf

Output will be:

[1,2] 3
[1,2,3] 6
[1,2,3,4] 10

Another key aspect of functions in ActionScript 3 is their ability to form closures and handle asynchronous operations, which we’ll look at next.