Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AS3 Casting one type to another

I have a base class called Room and a subclass called Attic, and another called Basement.

I have a controller class that has an attribute called CurrentLocation which is type Room. The idea is I want to be able to put Attic or Basement in that property and get it back, then cast that to whatever type it is.

So if on the controller the content is of type Attic, I'm trying to figure out how to explicitly cast it. I thought I knew but its not working... Here's what I thought it would be, borrowing from Java:

var myAttic:Attic = (Attic) Controller.CurrentLocation;

This gives me a syntax error:

1086: Syntax error: expecting semicolon before instance.

So how do you cast implicitly? Or can you? I could swear I've done this before as as3.

like image 638
Bruce Van Horn Avatar asked Mar 12 '12 00:03

Bruce Van Horn


1 Answers

Here are your options for casting in ActionScript 3:

  1. Use as.

    var myAttic:Attic = Controller.CurrentLocation as Attic; // Assignment.
    (Controller.CurrentLocation as Attic).propertyOrMethod(); // In-line use.
    

    This will assign null to myAttic if the cast fails.

  2. Wrap in Type().

    var myAttic:Attic = Attic(Controller.CurrentLocation); // Assignment.
    Attic(Controller.CurrentLocation).propertyOrMethod(); // In-line use.
    

    This throws a TypeError if the cast fails.

like image 112
Marty Avatar answered Oct 07 '22 19:10

Marty