views:

141

answers:

1

is it not possible to define a static const array? i would like to have an optional parameter to a function that is an array of colors,

private static const DEFAULT_COLORS:Array = new Array(0x000000, 0xFFFFFF);

public function myConstructor(colorsArray:Array = DEFAULT_COLORS)
{
}

i know i can use ...args but i actually wanting to supply the constructor with 2 separate arrays as option arguments.

+2  A: 

Not possible, but you could this to simulate this behaviour:

private static const DEFAULT_COLORS:Array = new Array(0x000000, 0xFFFFFF);

public function myConstructor(colorsArray:Array = null)
{
    colorsArray = colorsArray ? colorsArray : DEFAULT_COLORS;
}

This will not work if your function is coded in a way such that null could be a valid value (to signal some condition, for instance), but probably that's not the case here.

Edit

If you plan to write to colorsArray in myConstructor, it would be wise to make a copy of DEFAULT_COLORS here:

colorsArray = colorsArray ? colorsArray : DEFAULT_COLORS.slice();

The reference to the DEFAULT_COLORS Array is constant, but its contents are not, so you could accidentally change your default values.

Juan Pablo Califano
thanks for the answer. works great. however, can you explain how i might accidentally change the default colors by not making a copy of the array? i'm not quite following what you mean.
TheDarkInI1978
@TheDarkIn1978. Sure. If you call the function with no parameters (or null) `colorsArray` will be a reference to `DEFAULT_COLORS`. I.e. it will give access to the same object. Then, if at some point in your function you do something like `colorsArray[0] = 0xffcc99;` or `colorsArray.splice(0,1);` or anything that modifies `colorsArray`, you will be changing the contents of `DEFAULT_COLORS`, probably without intending to do so. This is because colorsArray will be a reference to the same object that the `DEFAULT_COLORS` const references. Making a copy, that can't possibly happen.
Juan Pablo Califano