[AS3]How can I casting AObject to BObject automatically? - actionscript-3

I want to cast AObject to BObject automatically like toString().
My original code is below:
var a:AObject = new AObject();
var b:BObject = new BObject();
someFunction(b:BObject):void{}
someFunction(a.toBObject()); // no error
trace(a.toString()); //[object AObject]
So, I want to finish it like toString()
someFunction(a); //TypeError: Error #1034: Type Coercion failed
trace(a); //[object AObject]
How can I solve it?

If you are wanting to pass two arbitrary objects that might be handled similarly, you can use interfaces to "hide" the differences and expose the seemingly shared functionality. I'm not saying this is good practice for your situation, but it is a solution. As in...
public interface CommonGround
{
function toString() : String;
}
public class AObject implements CommonGround
{
public function toString() : String
{
// implement here
}
}
public class BObject implements CommonGround
{
public function toString() : String
{
// implement here
}
}
...and then use them elsewhere in the program...
public someFunction( obj:CommonGround ) : void
{
trace( obj.toString() );
}
...or...
var obj:CommonGround = new AObject();
trace( obj.toString() );

Related

How can I solve 'Duplicate Constructor' error in Haxe?

In Haxe, I created a class named MyClass like:
class MyClass {
var score: String;
public function new (score: Int) {
this.score = Std.string(score);
}
public function new (score: String) {
this.score = score;
}
}
I need multiple constructors but Haxe does not allow me to do. It throws this error from building phase:
*.hx:*: lines * : Duplicate constructor
The terminal process terminated with exit code: 1
How can I solve this problem?
This is known as method overloading, which is not supported by Haxe apart from externs (but might be in the future). There's multiple ways you could work around this.
A common workaround in the case of constructors would be to have a static "factory method" for the second constructor:
class MyClass {
var score:String;
public function new(score:String) {
this.score = score;
}
public static function fromInt(score:Int):MyClass {
return new MyClass(Std.string(score));
}
}
You could also have a single constructor that accepts both kinds of arguments:
class MyClass {
var score:String;
public function new(score:haxe.extern.EitherType<String, Int>) {
// technically there's no need for an if-else in this particular case, since there's
// no harm in calling `Std.string()` on something that's already a string
if (Std.is(score, String)) {
this.score = score;
} else {
this.score = Std.string(score);
}
}
}
However, I wouldn't recommend this approach, haxe.extern.EitherType is essentially Dynamic under the hood, which is bad for type safety and performance. Also, EitherType is technically only intended to be used on externs.
A more type-safe, but also slightly more verbose option would be haxe.ds.Either<String, Int>. Here you'd have to explicitly call the enum constructors: new MyClass(Left("100")) / new MyClass(Right(100)), and then use pattern matching to extract the value.
An abstract type that supports implicit conversions from String and Int might also be an option:
class Test {
static function main() {
var s1:Score = "100";
var s2:Score = 100;
}
}
abstract Score(String) from String {
#:from static function fromInt(i:Int):Score {
return Std.string(i);
}
}
Finally, there's also an experimental library that adds overloading support with macros, but I'm not sure if it supports constructors.
I recommend to use type parameter
class MyClass<T> {
var score:String;
public function new(score:T) {
this.score = Std.string(score);
}
}
You can also use type parameter at constructor
class MyClass {
var score:String;
public function new<T>(score:T) {
this.score = Std.string(score);
}
}
However, T used at constructor fails at runtime (CS and Java), it is not fixed yet (Haxe 4). Otherwise, you could do this
class MyClass {
var score:String;
#:generic public function new<#:const T>(score:T) {
this.score = Std.is(T, String) ? untyped score : Std.string(score);
}
}
which nicely produce code like this (CS)
__hx_this.score = ( (( T is string )) ? (score) : (global::Std.#string(score)) );
causing Std.string() to be called only if T is not a String.
Hej,
With a simple example as it is, you can just do something like that function new( ?s : String, ?n : Int ){} and Haxe will use the correct argument by type. But you'll be able to do new() and maybe you don't want.

call function of class on instance of class

I have some code that generates answers based on the user input. But in somecases i need to update the values later by calling SetAnswers But when i compile my code i get the following error:
NullReferenceException: Object reference not set to an instance of an object
I get this error on the line marked by the arrow.
See below for my code:
public class Generate_Questions : MonoBehaviour{
public Question q5, q4;
void Start(){
q4 = create_question("Select object to edit", EXTERNAL);
Visual_Question vq1 = new Visual_Question(1, q4, new vector(1,1,1), Ui, Canvas);
vq1.draw_question();
}
void Update(){
}
public class Visual_Question : Generate_Questions{
public Visual_Question(int order_id, Question q, Vector2 loc, Dictionary<string, RectTransform> ui, RectTransform canvas){
}
public void draw_question(){
q4.SetAnswers(new Answer[]{ <--------- this generates the error.
new Answer(null, "Select an option")
});
}
}
public class Question{
public string text;
public int answers_loc;
public List<Answer> answers;
public Question(string q_text, int answers_loc){
answers = new List<Answer>();
this.text = q_text;
this.answers_loc = answers_loc;
}
public void SetAnswers(Answer[] c_answers){
foreach(Answer answer in c_answers){
this.answers.Add(answer);
}
}
public bool CheckIfAnswersAvailable(){
if(answers.Count > 0){
return true;
}else{
return false;
}
}
public int QuestionLocation(){
return answers_loc;
}
}
public Question create_question(string text, int a_type){
Question Q = new Question(text, a_type);
return Q;
}
public interface IAnswer{
string GetText();
string GetDataType();
object GetValue();
Question GetNextQuestion();
}
public class Answer : IAnswer{
public string text;
public Question next = null;
public int? action = null;
public Element obj = null;
public string property = null;
public float? value = null;
public Answer(Question next, string text){
this.text = text;
this.next = next;
}
public Answer(Question next, string text, Element obj, int? action){
this.action = action;
this.text = text;
this.next = next;
this.obj = obj;
}
public Answer(Question next, string text, Element obj, int? action, string property, float? value){
this.action = action;
this.next = next;
this.text = text;
this.obj = obj;
this.property = property;
this.value = value;
}
public string GetText(){
return text;
}
public string GetDataType(){
throw new System.NotImplementedException();
}
public object GetValue(){
return value;
}
public Question GetNextQuestion(){
return next;
}
}
}
how would i go about fixing this problem? I am a complete newbie to c#. So my question may be already answered but i just dont know what i am looking for.
I assume that IAnswer[] is an interface and since you are trying to initialize an abstract object you get that runtime exception
NullReferenceException: Object reference not set to an instance of an object
if you want to create instance of IAnswer object you have to restructure it like class or structure.
Your class Visual_Question derives from Generate_Questions, so the member q4 that you use en draw_question is not initialized. This is not the member of Generated_Questions but a member of Visual_Question that is not initialized.
In Generate_Questions you are creating a new instance of Visual_Question and then immediately calling draw_question on that new instance. You now have 2 instances of a question (both derive from Generate_Questions), but only one of them has had the Start method, which initializes q4 called. If, however, you attempt to call Start from your second instance, you're going to find yourself in an infinite series of recursive calls and quickly crash with a different error (a stack overflow in this case).
One issue with the current code is that Generate_Questions sounds more like an action than a class. I'd suggest removing the inheritance from Visual_Question and make that an interface that you would implement on Question. Question should probably have the create_question method removed. That probably belongs in a MonoBehavior script (technically it's a factory method -- look up the factory pattern -- I'm not going to go into it here since this is a beginner topic).
Something like (obviously not complete):
public class Generate_Questions : MonoBehaviour
{
private IVisualQuestion q4;
void Start()
{
q4 = new Question("Select object to edit", EXTERNAL);
q4.DrawQuestion(new vector(1,1,1), Ui, Canvas)
}
void Update() {}
}
public interface IVisualQuestion
{
void DrawQuestion(Vector2 loc, Dictionary<string, RectTransform> ui, RectTransform canvas);
}
public class Question : IVisualQuestion
{
// ... insert the Question constructor and code here ...
// Implement VisualQuestion interface
public void DrawQuestion(Vector2 loc, Dictionary<string, RectTransform> ui, RectTransform canvas)
{
this.SetAnswers(new Answer[]{new Answer(null, "Select an option")});
}
}
In general, you probably don't need inheritance. As you learn more C#, you'll discover that when inheritance is going to help it will be clear. More often than not, using an interface is a far better and flexible approach. As a commenter noted, you probably don't want to inherit from MonoBehavior. You really only need that for classes that the Unity Engine is going to directly handle.
Another note: the convention in C# is to name methods, variables, etc. in PascalCase, not using underscores to separate words.

convert class to object actionscript 3

I`m tring to covert class to json.
The class is:
package com.globalData{
public class userSite {
private var uID:int,uName:String,uSocket:int,uZone:int,uRoom:int;
public function user(ID:int,Name:String,ZoneID:int,RoomID:int,socketID:int){
uID = ID;
uName = Name;
uSocket = socketID;
uZone = ZoneID;
uRoom = RoomID;
}
public function getName():String{
return uName;
}
public function getID():int{
return uID;
}
public function getZoneID():int{
return uZone;
}
public function getRoomID():int{
return uRoom;
}
public function getSocket():int{
return uSocket;
}
}
}
Im tryed to do:
json(Object(roomVar));
But its not work (JSOn is function on the main class)
Im need to convert the class to json and send the json -> Socket
How can i do it?
There are a few issues with your code above:
It doesn't appear as though your userSite class has a constructor. Instead, you've opted to have a user function that takes in all of the initialization arguments
You're using functions where you should probably be using accessor methods, sometimes called a getter.
public function getName():String { return uName;} would become public function get name():String { return uName;}
Instead of calling getName(), you would access name as a property: instance.name
You're attempting to pass an Object to the JSON.decode method, this method expects a String. Something like "{ 'a':1, 'b':[1,2,3] }" would be an acceptable parameter. This would return an object with two properties a and b, a would contain the value 1, and b would contain an array with the elements 1, 2, and 3. What you are looking for is actually the JSON.encode method which accepts an Object and converts it to a String (which can be parsed as JSON).
I suggest you convert all of your getXYZ() functions to accessors, this will allow an instance of that class to be read as a collection of properties, which will in turn allow the JSON.encode function to create a JSON string object from it:
package com.globalData
{
public class UserSite {
private var uID:int,uName:String,uSocket:int,uZone:int,uRoom:int;
public function UserSite(ID:int,Name:String,ZoneID:int,RoomID:int,socketID:int):void{
uID = ID;
uName = Name;
uSocket = socketID;
uZone = ZoneID;
uRoom = RoomID;
}
public function get name():String{
return uName;
}
public function get ID():int{
return uID;
}
public function get zoneID():int{
return uZone;
}
public function get roomID():int{
return uRoom;
}
public function get socket():int{
return uSocket;
}
}
}
Usage:
var roomVar:UserSite = new UserSite(1, 'Name', 2, 3, 4);
trace(JSON.encode(roomVar as Object));
Output:
{"ID":1,"name":"Name","socket":4,"roomID":3,"zoneID":2}

Type preservation failing with RemoteClass

Consider the following example dataclass:
[RemoteClass]
public class SOTestData {
public var i:int;
public function SOTestData(i:int) {
this.i = i;
}
}
As I understand, the RemoteClass metadata-tag should ensure that when an object of this class gets sreialized, the type information is preserved.
I used the following program to test:
public class SOTest extends Sprite {
public function SOTest() {
var data:SharedObject = SharedObject.getLocal("SOTest");
if (data.data.object) {
try {
var stored:SOTestData = data.data.object;
trace(stored.i);
} finally {
data.clear();
}
}
else {
data.data.object = new SOTestData(15);
data.flush();
}
}
}
Here the first run writes the data, seconds reads and clears. Running this, I still get a class cast error. Indeed, in the SharedObject there is no type information stored.
I don't think i'm using the metadata wrong, could it maybe be that the compiler doesn't know what to do with it? I don't get any compiler errors/warnings, although when i use some inexistant tag it doesn't complain either. I'm using Flex 4.6 SDK with FlashDevelop as IDE.
EDIT:
Below is the shared object. As you can see, the type is saved as "Object" instead of the actual type.
so = [object #2, class 'SharedObject'] {
data: [object #0, class 'Object'] {
object: [object #1, class 'Object', dynamic 'False', externalizable 'False'] {
i: 15,
},
}
}
I've only used RemoteClass for making AMF RemoteObject calls; I didn't think it had anything to do w/ Shared Objects. Per the docs
Use the [RemoteClass] metadata tag to register the class with Flex so
that Flex preserves type information when a class instance is
serialized by using Action Message Format (AMF). You insert the
[RemoteClass] metadata tag before an ActionScript class definition.
The [RemoteClass] metadata tag has the following syntax:
As best I can tell from the code you provided, you are not serializing the object in AMF format.
I believe your class cast error is due to the fact that you aren't casting your class. Shared Objects always come back as generic Objects. Try this:
var stored:SOTestData = data.data.object as SOTestData ;
Here is some code from an application I use. First the value object which will get serialized in a shared object:
package com.login.vos
{
[RemoteClass(alias="com.login.vos.UserVO")]
public class UserVO
{
public function UserVO()
{
}
public var firstName :String;
public var lastName :String;
public var userID :Number;
}
}
The the code to save the object:
public static function saveUserVO(userVO:UserVO):void{
var userSharedObject :SharedObject = SharedObject.getLocal('userVO') ;
userSharedObject.data.userVO = userVO;
userSharedObject.flush();
}
And finally, the code to load the objecT:
public static function getUserVO():UserVO{
var userSharedObject :SharedObject = SharedObject.getLocal('userVO')
if(userSharedObject.size <=0){
return null;
}
return userSharedObject.data.userVO as UserVO;
}
The only obvious difference between this and the code by the original poster is that I'm specifying an alias in the RemoteClass metadata.

Getting a return value or exception from AspectJ?

I am able to get the signature and arguments from advised method calls, but I cannot figure out how to get the return values or exceptions. I'm kind of assuming that it can be done in some way using around and proceed.
You can use after() returning and after() throwing advices as in beginning of the following document. If you're using #AspectJ syntax please refer to #AfterReturning and #AfterThrowing annotations (you can find samples here).
You can also get return value using after returing advice.
package com.eos.poc.test;
public class AOPDemo {
public static void main(String[] args) {
AOPDemo demo = new AOPDemo();
String result= demo.append("Eclipse", " aspectJ");
}
public String append(String s1, String s2) {
System.out.println("Executing append method..");
return s1 + s2;
}
}
The defined aspect for getting return value:
public aspect DemoAspect {
pointcut callDemoAspectPointCut():
call(* com.eos.poc.test.AOPDemo.append(*,*));
after() returning(Object r) :callDemoAspectPointCut(){
System.out.println("Return value: "+r.toString()); // getting return value
}
Using an around() advice, you can get the return value of the intercepted method call by using proceed(). You can even change the value returned by the method if you want to.
For instance, suppose you have a method m() inside class MyClass:
public class MyClass {
int m() {
return 2;
}
}
Suppose you have the following aspect in its own .aj file:
public aspect mAspect {
pointcut mexec() : execution(* m(..));
int around() : mexec() {
// use proceed() to do the computation of the original method
int original_return_value = proceed();
// change the return value of m()
return original_return_value * 100;
}
}