maguskrool
Technical User
Hi.
I have created several custom classes:
- Category, containing a string with the category's name.
- SubCategory, extends Category.
- CategoryList, containing an array of Category instances and a function getCategoryByName.
- SubCategoryTracer, with a function subTrace that traces the name of a given SubCategory.
When I use subTrace, if the argument is a direct SubCategory, it works fine, but if it's the result of getCategoryByName, even when it does return a SubCategory object, I get the following error:
1118: Implicit coercion of a value with static type tests:Category to a possibly unrelated type tests:SubCategory.
How can I get this to work? Thanks in advance.
I have created several custom classes:
- Category, containing a string with the category's name.
- SubCategory, extends Category.
- CategoryList, containing an array of Category instances and a function getCategoryByName.
- SubCategoryTracer, with a function subTrace that traces the name of a given SubCategory.
When I use subTrace, if the argument is a direct SubCategory, it works fine, but if it's the result of getCategoryByName, even when it does return a SubCategory object, I get the following error:
1118: Implicit coercion of a value with static type tests:Category to a possibly unrelated type tests:SubCategory.
How can I get this to work? Thanks in advance.
Code:
package tests{
//
public class Category {
private var _sName:String;
public function set catName (s:String):void {
_sName = s;
}
public function get catName ():String {
return _sName;
}
}
}
package tests{
//
public class SubCategory extends Category{
}
}
package tests{
//
public class CategoryList {
private var _aList:Array = new Array();
public function get catList ():Array {
return _aList;
}
public function addCategory(cat:Category):void {
_aList.push(cat);
}
public function getCategoryByName(s:String):Category {
for (var i:int = 0; i < _aList.length; i++) {
if (_aList[i].catName == s) {
return _aList[i];
}
}
return null;
}
}
}
package tests{
//
public class SubCategoryTracer {
public function subTrace(sub:SubCategory):void {
trace ("name: "+sub.catName);
}
}
}
//
//.fla, frame1
import tests.*
var cat:Category = new Category();
cat.catName = "category_1";
var sub:SubCategory = new SubCategory();
sub.catName = "subcategory_1";
var ctl:CategoryList = new CategoryList();
ctl.addCategory (cat);
ctl.addCategory (sub);
var sct:SubCategoryTracer = new SubCategoryTracer ();
trace (ctl.catList); //[object Category],[object SubCategory]
trace (ctl.getCategoryByName("category_1")); //[object Category]
trace (ctl.getCategoryByName("subcategory_1")); //[object SubCategory]
sct.subTrace (sub); //name: subcategory_1
sct.subTrace (ctl.getCategoryByName("subcategory_1")); //error mentioned above