How do one cast a instance of subclass to its superclass? - actionscript-3

So I have this superclass grid class, and a subclass of the grid class named GrassTile1, GrassTile2, etc... all of the instance of the subclasses are stored in an array. How am I suppose to convert the instance of subclass to its superclass referencing to the array?
private var backgroundGrid = []; //the array which the grids are stored in, in the main class.
public class Grid extends MovieClip
{
protected var node :PathfindNode; //the variable I wish to access, from an instance of subclass.
public function Grid(){
node = new PathfindNode();
}
}
public class GrassTile1 extends Grid { //every subclass of Grid will extends Grid
public function GrassTile1() {
// constructor code
}
}
function getBackgroundGrid(i:int,j:int):Grid{ //in the main class
return Grid(backgroundGrid[i][j]); // this line gives me an error
}
TypeError: Error #1034: Type Coercion failed: cannot convert GrassTile1#2905d5f1 to Grid.
I've tried accessing backgroundGrid[i][j].node and other ways to work around that I could think of and failed. Any Idea?

Try :
return backgroundGrid[i][j] as Grid;
Personally, Grid seems like a bad class name to use. I think Tile makes more sense, as that GrassTile1 is not a grid as I logically understand a grid. A grid might contain a collection of tiles, so doesn't sound logical to use that as a class name for tiles.
Also, where is the line where you actually call the getBackgroundGrid method ? You should try casting there, as opposed to in that method. I believe that will solve the problem.
I can't verify the line throwing the error, so we are assuming that it's the return statement. But, it could be on the other side where you are calling getBackgroundGrid.
UPDATE : I have tried a .fla using what you are describing and it works just fine, I get no error. Which is why I'm thinking we are missing something here and maybe the definition of the class is not being used. Can you put a trace in your constructors to verify what you expect is actually happening ?

Related

Run a 'constructor' or function, after class fields initialized, in a sane way?

I'd like to use ES6 public class fields:
class Superclass {
constructor() {
// would like to write modular code that applies to all
// subclasses here, or similarly somewhere in Superclass
this.example++; // does NOT WORK (not intialized)
//e.g. doStuffWith(this.fieldTemplates)
}
}
class Subclass extends Superclass {
example = 0
static fieldTemplates = [
Foo,
function() {this.example++},
etc
]
}
Problem:
ES6 public fields are NOT initialized before the constructors, only before the current constructor. For example, when calling super(), any child field will not yet have been defined, like this.example will not yet exist. Static fields will have already been defined. So for example if one were to execute the code function(){this.example++} with .bind as appropriate, called from the superclass constructor, it would fail.
Workaround:
One workaround would be to put all initialization logic after all ES6 public classes have been properly initialized. For example:
class Subclass extends Superclass {
example = 0
lateConstructor = (function(){
this.example++; // works fine
}).bind(this)()
}
What's the solution?
However, this would involve rewriting every single class. I would like something like this by just defining it in the Superclass.constructor, something magic like Object.defineProperty(this, 'lateConstructor', {some magic}) (Object.defineProperty is allegedly internally how es6 static fields are defined, but I see no such explanation how to achieve this programatically in say the mozilla docs; after using Object.getOwnPropertyDescriptor to inspect my above immediately-.binded-and-evaluated cludge I'm inclined to believe there is no way to define a property descriptor as a thunk; the definition is probably executed after returning from super(), that is probably immediately evaluated and assigned to the class like let exampleValue = eval(...); Object.defineProperty(..{value:exampleValue})). Alternatively I could do something horrible like do setTimeout(this.lateConstructor,0) in the Superclass.constructor but that would break many things and not compose well.
I could perhaps try to just use a hierarchy of Objects everywhere instead, but is there some way to implement some global logic for all subclasses in the parent class? Besides making everything lazy with getters? Thanks for any insight.
References:
Run additional action after constructor -- (problems: this requires wrapping all subclasses)
Can I create a thunk to run after the constructor?
No, that is not possible.
How to run code after class fields are initialized, in a sane way?
Put the code in the constructor of the class that defines those fields.
Is there some way to implement some global logic for all subclasses in the parent class?
Yes: define a method. The subclass can call it from its constructor.
Just thought of a workaround (that is hierarchically composable). To answer my own question, in a somewhat unfulfilling way (people should feel free to post better solutions):
// The following illustrates a way to ensure all public class fields have been defined and initialized
// prior to running 'constructor' code. This is achieved by never calling new directly, but instead just
// running Someclass.make(...). All constructor code is instead written in an init(...) function.
class Superclass {
init(opts) { // 'constructor'
this.toRun(); // custom constructor logic example
}
static make() { // the magic that makes everything work
var R = new this();
R.init(...arguments);
return R;
}
}
class Subclass extends Superclass {
subclassValue = 0 // custom public class field example
init(toAdd, opts) { // 'constructor'
// custom constructor logic example
this.subclassValue += toAdd; // may use THIS before super.init
super.init(opts);
// may do stuff afterwards
}
toRun() { // custom public class method example
console.log('.subclassValue = ', this.subclassValue);
}
}
Demo:
> var obj = Subclass.make(1, {});
.subclassValue = 1
> console.log(obj);
Subclass {
subclassValue: 1
__proto__: Superclass
}

AS3 How to declare an object without the dreaded "Conflict Exists" error?

I am designing a simple game in Flash and have come across this error. I have no idea how to go about this in actionscript and would appreciate any help.
Basically, I have a switch statement which creates an object of different type depending on each case (as I would prefer not to duplicate the same ten lines of code for each case) and I am getting a "conflict exists with definition in namespace internal" compiler error and I think I understand why.
switch(power){
case 1:
var Pow:objectOne = new objectOne();
break;
case 2:
var Pow:objectTwo = new objectTwo();
break;
}
My question however is this - what is the proper way of going about this?
I initially thought of declaring the variable before the switch statement which results in an "implicit coercion of a value of type object(One/Two) to an unrelated type Class" error. What am I missing here?
Aside from the compiler error you are experiencing, another problem here is that you are planning on using the pow variable later in your code, yet they are of different types. My suggestion is to use the benefits of Inheritance in OOP and create a base class that your two custom classes can inherit from. That way they are both technically of the same base type, while still giving you the freedom to customize each custom class, while keeping similar functionality in the base class.
Remember, OOP is here to always help you and is there to avoid issues like the one you have come across, but here is how I would do it, and I tested the following implementation in Flash CC 2014 and it compiled successfully:
Example .FLA:
var pow:BaseClass;
var power = 1;
switch(power){
case 1:
pow = new ObjectOne();
break;
case 2:
pow = new ObjectTwo();
break;
}
pow.whichObjectAmI(); // this will simply trace what object pow is
Base Class
package {
public class BaseClass {
public function BaseClass() {
// constructor code
}
public function whichObjectAmI() {
trace("I am the base class");
}
}
}
Object One
package {
public class ObjectOne extends BaseClass {
public function ObjectOne() {
// constructor code
}
override public function whichObjectAmI() {
trace("I am Object One!");
}
}
}
Object Two
package {
public class ObjectTwo extends BaseClass {
public function ObjectTwo() {
// constructor code
}
override public function whichObjectAmI() {
trace("I am Object Two!");
}
}
}
You can always inherit from any of ActionScript's classes as well like MovieClip, Button, etc. And by doing so, you're adding custom functionality on top of their functionality so 1) you don't have to rebuild a bunch of functionality, and 2) giving you the chance to reuse their functionality while adding your own custom code!
Disclaimer: My AS3 is a little rusty ;)
Of what type would the variable Pow be after the switch statement? objectOne or objectTwo? From the compiler's perspective objectOne and objectTwo could be totally different from each other (read: methods, fields,...)
So:
A) Keep variable name for both assignments but declare it before the switch-statement AND use a common base-type (object, MovieClip,...)
B) Have 2 different variables: var PowOne: objectOne and var PowTwo: objectTwo
I think option A would be preferable...

Call to a possibly undefined method '' through a reference with static type Class

I made small .fla file in Flash Professional, and I have added .as (ActionScript File) in Flash Professional, and I have added something like code below to .as (ActionScript file), but the error appears and I am trying to figure it out, but can't, so I decided to post it in here instead.
package
{
import flash.display.MovieClip;
public class Bag extends MovieClip
{
static var firstBag:String;
public static function set setFirstBag(value:String):void
{
firstBag = value;
}
public static function get getFirstBag():String
{
return firstBag;
}
}
}
and I called it like this:
button1.addEventListener(MouseEvent.CLICK, onClickFirstButton);
function onClickFirstButton(e:MouseEvent):void
{
Bag.setFirstBag("First slot in the bag has been filled up!");
}
But I have received this following error:
Call to a possibly undefined method setFirstBag through a reference
with static type Class.
What could I do wrong?
The .as file and .fla file are on the same folder.
if I changed the Bag class to static. The error will be like this:
The static attribute may be used only on definitions inside a class.
Your answer much appreciated!
Thank you!
You're useing get like it is a mettod, but thay are accessors for properties so intead of:
Bag.setFirstBag("First slot in the bag has been filled up!");
use
Bag.setFirstBag ="First slot in the bag has been filled up!";
A few additional thoughts...
While syntactically valid, the definition and naming of your getter and setter is confusing and atypical, which I think contributed to your confusion about the behavior. You've actually defined two separate properties, one is write-only ("setFirstBag") and one is read-only ("getFirstBag"). Usually you define a getter/setter as the same property (ex "firstBag"), and without any "get" or "set" in the property name, since that is what the getter/setter is defining for you. Example:
private static var _firstBag:String;
public static function get firstBag():String {
return _firstBag:
}
public static function set firstBag(value:String):void {
_firstBag = value;
}
// usage
Bag.firstBag = "stuff";
trace(Bag.firstBag); // "stuff"
Also, you may very well have a good reason to use a getter/setter here, or you might just prefer it, but from the code you posted you could just define a public static var to do the same thing. (If you did, refactoring into a getter/setter if you needed some side-effect logic would be trivial, since the public API remains the same.)

When using the 'Class' datatype, how can I specify the type so I only accept subclass of a specific class?

I've got a method that accepts a parameter of type Class, and I want to only accept classes that extend SuperClass. Right now, all I can figure out to do is this, which does a run-time check on an instance:
public function careless(SomeClass:Class):void {
var instance:SomeClass = new SomeClass();
if (instance as SuperClass) {
// great, i guess
} else {
// damn, wish i'd have known this at compile time
}
}
Is there any way to do something like this, so I can be assured that a Class instance extends some super class?
public function careful(SomeClass:[Class extends SuperClass]):void {
var instance:SuperClass = new SomeClass();
// all is good
}
If you are going to instantiate it anyway, why not accept an object instead which allows you to type it to :SuperClass?
careless(SomeClass);
//vs.
careless(new SomeClass);
Not too much of a problem there as far as your code goes.
There are a few differences though:
The object has to be created, because an object is required. If your function does not instantiate the class under some circumstances, this can be a problem. Additional logic to pass either an object or null can bloat the function call.
If you cannot call the constructor outside that function, it won't
work either.
All that is solved by the factory pattern. Pass a factory as the parameter that produces SuperClass objects.
function careful(factory:SuperClassFactory)
Your requirements:
I want to only accept classes that extend SuperClass
and
I need to pass in a Class so that it can be instantiated many times
by other objects later
Can be met by passing in an instance of the class you need, and using the Object.constructor() method.
public function careful(someInstance:SuperClass):void {
//you probably want to store classRef in a member variable
var classRef: Class = someInstance.constructor();
//the following is guaranteed to cast correctly,
//since someInstance will always be a descendant of SuperClass
var myInst:SuperClass = new classRef() as SuperClass;
}
More reading here.
You can't do that in ActionScript 3. In languages like C# you can do something like (forgive me if the syntax is off):
public void Careless<T>() where T : SuperClass
But AS3 does not have 'generics'. Unfortunately the only way I know how to do what you want is the way you have already done.
A pattern that might be more suitable for your use case might be something like:
class SuperClass
{
public static function careless():void
{
var instance:SuperClass = new SuperClass();
// ...
}
}
The only way to have static type checking in ActionScript 3 is to provide an instance of a class.
It is possible but it's expensive. You can use on a Class (not instance) the:
flash.utils.describeType
You then get an XML with a bunch of information including inheritance for that class. Like I said it's an expensive process and probably creating an instance and checking it will be in most cases faster.

How to assign a custom object to bytesArray? As3

I have a TActor class and a function to_bytes() inside it that should compress it to a bytes array as in this example: http://jacksondunstan.com/articles/1642
public function to_bytes():ByteArray
{
registerClassAlias("TActor",TActor);
var bytes:ByteArray=new ByteArray();
bytes.writeObject(this as TActor);
bytes.position=0;
trace(bytes.readObject());
bytes.position=0;
trace(bytes.readObject() as TActor);
return bytes;
}
However, the first trace prints undefined and the second one null instead of [object TActor].
What do I do wrong?
It's important to note that the this keyword returns the current instance of the object. What you are currently doing is attempting to pass the this instance to writeObject, which will only work if there is an instance of TActor instantiated. So it would work in this scenario:
In some class where you instantiate TActor:
var tactor:TActor = new TActor();
tactor.to_bytes();
Then it should serialize correctly.
Also as we discovered in the comments, TActor is of type MovieClip, currently you cannot use writeObject() on Objects of type MovieClip. More specifically any object that is a dynamic class cannot be used in writeObject. Changing it to Sprite solved this particular case.