idlackage
idlackage

Reputation: 2863

Type coercion fails when grabbing from an array

Say I have a class Person with a private array called children, containing Person objects. It has a method getChildren():Array { return this.children; }.

If I do trace(p.getChildren()[0]) (where p is an instance of Person), I can successfully print out whatever the first child is in the array. However, if I try to cast var firstChild:Person = p.getChildren()[0], I get an error saying Type Coercion failed: cannot convert []@a027b81 to classes.Person.

What is going wrong?

Upvotes: 0

Views: 42

Answers (1)

BadFeelingAboutThis
BadFeelingAboutThis

Reputation: 14406

When you do: var firstChild:Person = p.getChildren()[0] your not actually casting. Your just trying to stuff an Array into an object you've defined as a Person and that's why you receive the error.

To cast, you need to do one of the following:

var firstChild:Person = Person(p.getChildren()[0]); //this will error if the cast fails

var firstChild:Person = p.getChildren()[0] as Person; //this will return null if the cast fails

A better approach however, may be to use a Vector - which in AS3 is like an array but all the members have to be of the specified type. So something like this:

private var children_:Vector.<Person>;
public function getChildren():Vector.<Person>{ return this.children_; }

Then you could just do:

var firstChild:Person = p.getChildren()[0]

Because each member of the Vector is already defined as a Person object.


Also, you may want to consider using a getter method instead of getChildren.

public function get children():Vector.<Person> { return this.children_;}

Then you access it like a property (but can't set it).

Upvotes: 1

Related Questions