COMMUNITY

What does cast do, and does it relate to unification?

What exactly does cast do? My understanding is that a variable has a type, which indicates what type object it may be bound to. And of course object’s have type. Does cast alter the type of a variable or the type of an object? Or does it do something else?

Looking at the docs for safe cast, it looks like cast is side-effecting…

Does cast have anything to do with type unification?

When would you need to cast? I don’t mean in order to subvert the type system — I just mean, during regular use, when would you come upon the need to cast?

Thanks!

Not sure if you’re looking for a very technical “under the hood” explanation (which I don’t have) but I tend to use cast most in an object-oriented environment where I need to pass an object to a function which was written for a “relative” class. For example if I’m working in OpenFL it has MovieClip class, which extends Sprite class. If I have a function which is expecting a MovieClip as a parameter I could cast a Sprite to a MovieClip, and then pass it to the function and it should work as expected. The compiler would complain if I didn’t do the cast.

No, thank you, for now I’d just like to know how it works in practice.

Thanks for the Sprite <-- MovieClip example! I see.

Ok, so, cast allows an object of type A to be recognized by the compiler as an object of type B? But then what’s going on with the example in the manual where the example code has those casts each on one line all by itself?

The example code is just that, an example. It’s pared down to illustrate what’s possible, not actually what’s useful. :slight_smile:

Would be great to see a haxe.org blog post about the differences between coercion, casting (safe and unsafe), and unification. My understanding so far:

  • coercion: implicit automatic conversions done by the compiler for things like "hey" + 1 ==> “hey1”, or 5.7 + 1.

  • casting: the compiler taking your word for it that you can assign an A object to a B variable (ex. downcasting).

  • unification: the checking process to see if a given object can be assigned to a variable without a cast (?)

To actually change the type of an object (explicitly coerce) I figure some kind of copy ctor would be involved…

Thanks for any help and clarification on this! :slight_smile:

1 Like