Search code examples
functionargumentshaxe

Passing list of arbitrary function arguments in Haxe


In ActionScript I can use ... in a function declaration so it accepts arbitrary arguments:

function foo(... args):void { trace(args.length); }

I can then call the function passing an array:

foo.apply(this, argsArray);

I'd like to call the function with arguments of unknown type and count. Is this possible in Haxe?


Solution

  • Starting with Haxe 4.2, Haxe will have native support for rest arguments:

    function f(...args:Int) {
        for (arg in args) {
            trace(arg);
        }
    }
    
    f(1, 2, 3);
    

    ...args:Int is simply syntax sugar for rest:haxe.Rest<Int>. Only the last argument of a function can be a rest argument.

    You can also use ... to "spread" an array when calling a function with a rest argument:

    final array = [1, 2, 3];
    f(...array);