5.9 var and final

The var keyword allows declaring multiple variables, separated by comma ,. Each variable has a valid identifier and optionally a value assignment following the assignment operator =. Variables can also have an explicit type-hint.

var a; // declare local `a`
var b:Int; // declare variable `b` of type Int
// declare variable `c`, initialized to value 1
var c = 1;
// declare an uninitialized variable `d`
// and variable `e` initialized to value 2
var d,e = 2;

The scoping behavior of local variables, as well as variable shadowing is described in Blocks.

since Haxe 4.0.0

In Haxe 4, the alternative keyword final was introduced at the expression level. Variables declared with final instead of var can only be assigned a value once.

class Main {
  static public function main() {
    final a = "hello";
    var b = "world";
    trace(a, b); // hello, world
    b = "Haxe";
    trace(a, b); // hello, Haxe

    // the following line would cause a compilation error:
    // a = "bye";
  }
}

It is important to note that final may not have the intended effect with types that are not immutable, such as arrays or objects. Even though the variable cannot have a different object assigned to it, the object itself can still be modified using its methods:

class Main {
  static public function main() {
    final a = [1, 2, 3];
    trace(a); // [1, 2, 3]

    // the following line would cause a compilation error:
    // a = [1, 2, 3, 4];

    // but the following line works:
    a.push(4);
    trace(a); // [1, 2, 3, 4]
  }
}