Any type error

Total haxe beginner here. I have class A with a public prop theX

Then l have class B with a List that currently is populated with instances of class A but it could be other types aswell. In B l have a method that needs to pull out an instance from the List and set instanceA.theX = 1; but the compiler complains that there is no such prop on A. Is’nt this how Any could be used? What could be wrong here? Thanks

You need to promote type when you get instance:

final list:List<Any> = [new A()];
final a:A = list[0];
trace(a.x);

You can also use such typing, if all list items have same property:

final list:List<{x:Float}> = [new A()];
trace(list[0].x);

Great! Thanks @RblSb

You’ll have to check if the object is of type A before doing that, or you’ll get error at runtime.

final a = cast(list[0], A);
if (a != null) {
   trace(a.x);
}

@tubbs can you share what you are trying to do? List<Any> is rarely something you’d need.

l have already declared and instanced the List as an empty list in the constructor of B and then l have some methods in B like below:

addItem(someInstance:Any){

myList.add(someInstance);
}

setTheX(x:Int){
var aInstance:Any = myList[0];
aInstance.theX = x;
}

I guess that explains what l’m trying to achieve. How would you do that?

What I mean is, what are you storing in the list? If you are only storing object from A you can do List<A>, or maybe the object share a parent class you could use?

I would like the list to be able to hold more types than just A but they would all have theX property.

In that case @RblSb’s solution would work, List<{ theX: Int }>, and you don’t need any Any in the code with this.
It also work on functions function addItem(someInstance:{theX:Int}) {.

ok thanks alot!

That’s exactly how you will get a runtime error though. :smiley: A safe cast like that doesn’t return null on failure, it throws an exception. Maybe you were looking for Std.downcast().