Book Image

haXe 2 Beginner's Guide

5 (1)
Book Image

haXe 2 Beginner's Guide

5 (1)

Overview of this book

Table of Contents (21 chapters)
haxe 2
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Static typing


In haXe, once a variable has been declared and its type is known, it is not possible to assign a value of another type to it. Note however that the compiler allows you to redeclare a variable with the same name and another type. So, the following code compiles:

class Main
{
   public static function main()
   {
      var e : String;
      e = "String";
      var e : Int;
      e = 12;
   }
}

However, although this code compiles, you should not be doing this because it might be confusing to other developers or even to you as well, if you have to read your code several days later.

Therefore, to keep things simple, once a variable is typed, its type cannot be changed, and only values of this type can be assigned to it. So, the following wouldn't work:

class Main
{
   public static function main()
   {
      var e : String;
      e = "Test";
      e = 12;
   }
}

This is because 12 is of type Int and not of type String.

Also, note that if you try to read from a variable without having...