05 4 / 2010
Going untyped or Dynamic : the difference and how important it will be.
Hello,
Most of my fellow haXe developers may think that untyped is just like a block of code where everything acts like Dynamic. Well, that’s false, and I’m gonna explain in this post what both of these things really are.
So first, untyped. Untyped is a keyword that acts on a block of code and basically, it just tells the compiler to get out of your way when it comes to typing. One could see that as temporarily deactivating the typing sub-system.
On the other hand, there’s the Dynamic type. Dynamic really *is* a type, it’s just that it has a special behavior. It’s behavior is that it has an infinite number of fields (accessible in reading) and all of these fields also are Dynamic. That’s the basic thing of Dynamics, after that there are all the other things such as implementing Dynamic but I’m not gonna describe everything here. The language reference is there to do that.
No, if I talk about it today, it’s because I’m pretty sure many haXe programmers have been using untyped blocks in their code instead of Dynamics (maybe because it’s easier to just write “untyped”), and that worked since most of the platforms we have in the official compiler today are dynamic.
So, this code will certainly work on JS/Flash/Neko and even PHP :
var s : String;
s = “Hello”;
untyped s.something = 12;
But here, what we do want to achieve is really a Dynamic behavior (although that’s quite stupid to declare the variable as String, but that’s just for the sake of the example). So it would be better to write :
var s : String;
s = “Hello”;
var d : Dynamic;
d = s;
d.something = 12;
Well, we could have done it with a bit less lines but I wanted to keep things crystal clear. Here, we will achieve the same behavior as in the first example, but instead of just switching the typing system to off, we ask it to take care of making the code work. In the platforms we have in the compiler at the moment, that’s not a problem because they are dynamic (not C indeed but it’s pretty young in the compiler).
Now, the Java target is coming, and although I can’t say if it will ever make it into the official distribution I do hope so. And since Java is really a static language, one will have to use the Dynamic type as that will ensure that the compiler will take care of doing all the magic things for you.
Want more explanations? Have any questions or comment?
Permalink 4 notes