0
votes

I have something like:

class A { }
class B extends A { }

Then I'm trying to cast an instance of A to B:

var a:A = obtainAInstance();
var b:B = B(a);

To this, I get the following error:

TypeError: Error #1034: Type Coercion failed: cannot convert A to B.

What could the cause of this be?

2

2 Answers

3
votes

Your a object is an A instance, but since A is the parent class rather than B, it cannot be a B instance. Thus, you can't perform such a cast.

If your function returns a B instance, you can cast a back to a B, and access all its B members, because the object is in fact a B:

var a:A = obtainBInstance();
var b:B = B(a);
0
votes

try var b:B = a as B;

        var o:Object = new Object();
        var ed:EventDispatcher = o as EventDispatcher;//this works
        //var ed:EventDispatcher = EventDispatcher(o); //this causes an error

however you may have problems with such B instance if calling properties not defined its super - A