i have no idea why the following code doesn’t work.
i’m simply passing and then repassing Shape objects as a rest parameter. when the objects arrive at the final function, they trace as [object Shape], but then on the next line i receive a type coercion failure, stating it couldn’t be converted into a Shape.
output:
[object Shape],[object Shape]
TypeError: Error #1034: Type Coercion failed: cannot convert []@27b68921 to flash.display.Shape.
at Test/receiver()
at Test/passer()
at Test()
code:
package
{
import flash.display.Sprite;
import flash.display.Shape;
public class Test extends Sprite
{
public function Test()
{
//Create Shapes
var myFirstShape:Shape = new Shape();
myFirstShape.graphics.beginFill(0);
myFirstShape.graphics.drawRoundRect(0, 0, 100, 100, 50);
var mySecondShape:Shape = new Shape();
mySecondShape.graphics.beginFill(0);
mySecondShape.graphics.drawRoundRect(0, 0, 100, 100, 50);
//Pass Shapes
passer(myFirstShape, mySecondShape);
}
private function passer(...items):void
{
//Pass Shapes Again
receiver(items);
}
private function receiver(...items):void
{
//Rest Trace As [object Shape], [object Shape]
trace(items);
//Type Coercion Failed ??!!
for each (var element:Shape in items)
{
trace(element);
}
}
}
}
This is a bit counter intuitive at first sight, but it actually makes sense…
When you declare a rest parameter, the arguments that you actually pass are wrapped in an Array at runtime.
That means, if you do:
Your function will receive an Array with 3 values.
This is exactly what’s going on here:
ìtemsis itself an Array in the body ofpasser. But when you callreceiver, this Array that contains 2 shapes is wrapped in another Array, because you declared thatreceivertook a rest parameter.When your loop in
receivertries to convert each item into a Shape, it fails (because you can’t convert anArrayinto aShape).You could see this changing your code a bit:
So, you have a couple of options to fix this, depending on what you really want to achieve.
1) Have
receiver“unwrap” the rest parameters to get the inner array. Basically loop thoroughitems[0]instead ofitems.2) Change you function signature to:
3) Change the way you call receiver so the array is passed as a list of arguments:
The effect of this would be equivalent to doing this:
Except it handles the list of items dynamically, of course.
If you really need
passerto take a rest parameter, you could go with option 3). Otherwise, I’d choose Option 2). Option 1) is the one I like the least, as it’s the most brittle, but it’s also a valid option.