Getting Some ...rest

Getting Some ...rest

Posted by hasan on Thu, 05/08/2008 - 16:54

Thought I'd blog about this since I haven't seen this posted before and it comes up from time to time. With AS3, we got access to a new function parameter, the ...rest parameter, which allows us to pass in a dynamic list of parameters for usage by our functions. Here's an example:

// Method in SomeClass
public function someMethod(...rest):void
{
    for (var i:uint=0; i < rest.length; i++)
    {
        trace(rest[i]);
    }
}

That will trace out each ...rest parameter that you pass to the method call like so:

// Usage from SomeOtherClass
var sc:SomeClass = new SomeClass();
      sc.someMethod(arg1, arg2, arg3, arg4);

This allows a lot of flexibility because those arguments can be simple (String, Number, etc) or complex (Array, Object, etc). But, what if someMethod() is part of SWC library that you may or may not have access to and you want to capture those ...rest arguments and pass them to SWC class?

Well, the easiest way that I've found is to use the built-in arguments object in your local code and then pass that to the SWC class that's expecting the ...rest array. Here's what I mean:

// Usage from LocalClass
public function someMethod(arg1:String, arguments:Object=null):void
{
    var sc:SomeClass = new SomeClass();
          sc.someMethod(arguments);
}

This way you can expose LocalClass.someMethod(), accept the concrete parameters that it expects and pass on the dynamic parameters that SomeClass.someMethod() expects.

Smiling