views:

108

answers:

2

Hello I've started to learning AS3 from one book and found something I don't understand.

Ellipse(_board[row][column]).fill = getFill(row, column);
  • _board is two dimensional array of Ellipse type, so I just dont understand why is Ellipse(Ellipse object) used when it apparently works without it, or I haven't seen any changes when I omitted it.
+2  A: 

Ellipse(_board[row][column]) is a type cast Type(object) Because you can push anything into an Array the compiler doesn't know what kind of objects are stored within the Array. So it is good style to cast objects if you retrive them from an Array to their correct type.

This has several benefits:

  • if such an object is not of the type you expect or null, you will know when you typecast instead of getting an error later somewhere far away
  • the code executes a bit faster if you are explicit about the types
  • if you use a good IDE it can provide you with autocompletion when it knows the types
maxmc
Thanks for explanation, AS3 casting syntax confused me a little
uther.lightbringer
A: 

_board is a multidimensional array filled first with Arrays. In the BoardDisplay.mxml

(Hello! Flex 4 : Chapter 3. Hello Spark: primitives, comp... > FXG and MXML graphics—building a game.. - Pg. 80) ,

<Graphic version="1.0" viewHeight="601" viewWidth="701"
  xmlns=" library://ns. adobe. com/flex/spark"
  xmlns:fx=" http://ns. adobe. com/mxml/2009"
  xmlns:mx=" library://ns. adobe. com/flex/halo"
  initialize="createBoard()"
  click=" clickHandler(event)">

initialize calls createBoard().

private function createBoard():void {
    newGame();
    _board = new Array(6);
    for (var row:int = 0; row < 6; row++) {
        _board[row] = new Array(7);
        for (var col:int = 0; col < 7; col++) {
            _board[row][col] = addEllipse(row, col); //Magic Happens!
        }
    }
}

addEllipse returns Ellipse to each entry in _board

private function addEllipse(row:int, col:int):Ellipse {
    var ellipse:Ellipse = new Ellipse();
    ellipse.x = 4 + col*100;
    ellipse.y = 5 + row*100;
    ellipse.width = 90;
    ellipse.height = 90;
    ellipse.fill = getFill(row,col); // Magic Found !
    ellipse.stroke = new SolidColorStroke(0x000000, 1, 1.0, false,"normal", null, "miter", 4);
    boardGroup.addElement(ellipse);
    return ellipse;
}

The author casted it as maxmx said but did not really need to as all the entries were of type Ellipse so

Ellipse(_board[row][column]).fill = getFill(row, column);

can work as

_board[row][column].fill = getFill(row, column);
phwd