haXe

Properties

Properties are a specific way to declare class fields, and can be used to implement several kind of features such as read-only/write-only fields or fields accessed through getter-setter methods.

Here's a property declaration example :

class C {

 public var x(getter,setter) : Int;

}

The values for getter and setter can be one of the following :

  • a method name that will be used as getter/setter
  • null if the access is restricted
  • defaultif the access is a classic field access
  • dynamic if the access is done through a runtime-generated method

Sample

Here's a complete example :

class C {
   public var ro(default,null) : Int;
   public var wo(null,default) : Int;
   public var x(getX,setX) : Int;

   private var my_x : Int;

   private function getX() {
       return my_x;
   }

   private function setX( v : Int ) {
      if( v >= 0 )
         my_x = v;
      return my_x;
   }

}

Using properties declaration, we declare three public fields in the class C :

  • outside the class code, the field ro is read only
  • outside the class code, the field wo is write only
  • the field x is accessed through a pair of getter/setter methods

For instance, the following two functions are equivalent, although the methods getX and setX are private and then can't be accessed directly as in f2 :

    var c : C;
    function f1() {
        c.x *= 2;
    }
    function f2() {
        c.setX(c.getX()*2);
    }

Important Remarks

It's important to know that such features are only working if the type of the class is known. There is no runtime properties handling, so for instance the following code will always trace null since the method getX will never be called :

    var c : Dynamic = new C();
    trace(c.x);

The same goes for read-only and write-only properties. They can always be modified if the type of the class is unknown.

On another side, please notice that you have to return a value from the setter function elsewhat the compiler will complain.

Dynamic Property

The additional dynamic access can be used to add methods at runtime, it's quite a specific feature that should be used with care. When a dynamic field x is accessed for reading, the get_x method is called, when accessed for writing the set_x method is called :

class C {
    public var age(dynamic,dynamic) : Int;
    public function new() {
    }
}

class Test {
    static function main() {
        var c = new C();
        var my_age = 26;
        Reflect.setField(c,"get_age",function() { return my_age; });
        Reflect.setField(c,"set_age",function(a) { my_age = a; return my_age; });
        trace(c.age); // 26
        c.age++; // will call c.set_age(c.get_age()+1)
        trace(c.age); // 27
    }
}

«« Iterators | Optional Arguments »»

version #1118, modified 2008-05-03 10:47:31 by ponticelli