How do I check what type I am dealing with?
Simply said: I am looking for a Haxe equivalent for Java's instanceof
.
This is my specific problem:
I have a class Tile
which contains a field content
of type Unit
and a function get_content()
that returns the currently stored object. Unit
is an interface which is implemented in 3 classes Player
, Monster
and Item
. Also, i have more specific monsters (like Dragon
or Beast
) and I defined each in their own class. Each of them extends the Monster
class.
Now I want to execute different code depending on what type the object returned by tile.get_content()
is. For example if it is any object that inherits from the Monster
class myFunction1()
is called and if it is anything that extends the Item
class myFunction2()
is called.
How would I achieve this behaviour?
Thank you in advance.
Edit:
I found that if (Type.typeof(tile.get_content()) == Monster)
seems to be the way to go, but does this return true for types that inherit from the Monster
class aswell or only for objects of the generic class Monster
?
As suggested by George, Std.isOfType()
should be used.
To answer my own second question from the edit: It does return true
for objects of classes which inherit from the specified class.
The full code for my specific example would therefore be
if (Std.isOfType(tile.get_content(), Monster)) {
myFunction1();
} else if (Std.isOfType(tile.get_content(), Item)) {
myFunction2();
}
there's two:
if (tile.get_content() is Monster)
//and
if (Std.isOfType(tile.get_content(), Monster))