It may be surprising to believe that the data types are static in haXe, though typed dynamically! This is awesome, for it gives you freedom to just type a variable without defining its datatype at the same time it will not allow to assign other data types to be assigned to the same variable. The best of both worlds. Whether you come from a dynamic language like javascript or a statically typed language like actionscript 3, this will surprise you in the beginning for sure. Another cool thing (rather hot thing) about haXe is these datatype mismatch will be checked at compile time and if mismatched, will not be compiled! Just beautiful.
Here is an example code.
private function testDataType()
{
var a;
a = 2;
trace(a);
a = '2';
trace(a);
}
The compiler will throw an error saying “String should be Int”. But how it knew that the datatype is Int ?!! The catch is, when the variable is assigned a value for the first time, the datatype is defined for that variable at that point and there after can not be changed. In our case we defined it as Int when assigned the value for the first time.
This concept goes further to function arguements and return types as well.
private function testDataType(x)
{
trace(x);
}
If we call above function with two different types of data as
testDataType(2);
testDataType('test');
The compiler will trow an error saying data type mismatch.
Lastly if there is a return type example code is as below.
private function testDataType(x)
{
if (x==2)
{
return 2;
}else {
return 'hello';
}
}
Though we can assume to write something like above in a dynamic language, but haXe compiler will not compile this, instead throw an error saying data type mismatch.
Happy haXe -ing.