dimanche 25 décembre 2016

How to properly override getters and setters in Haxe

I'm kind of new to Haxe but I have a lot of experience in ActionScript 3. Right now I'm porting one of my frameworks from AS3 to openfl, but I'm kind of stuck with getters and setters. Some of the framework components extends from openfl.display.DisplayObject (Sprite, to be exact) which already defines fields for width and height. But in my ComponentBase class I need to override these properties. In AS3 I'm doing it like this:

private var _width:Number = 0;

override public function get width():Number {
    return _width;
}
override public function set width(value:Number):void {
    _width = value;
}

But it doesn't work in Haxe. If I do it like this

override function get_width():Float {
    return _width;
}

It won't compile because it wants a physical field. But I also cannot redefine width and height values because they are already defined in base class.

You may ask why am I not using the values 'width' and 'height' defined in the base class. That's because sometimes I need to access those variables not thru the getter/setter accessors but directly. For example, I have a call to layout() method inside width and height setters, but I want to calculate it many times and call layout() only once.

Right now I decided to use Java-style getters and setters to make the job done, but it's not the best way. E.g.

public function setWidth(value:Float):Void {
    _width = value;
}

So, the question is: is it possible to make Haxe getters and setters use some value which has the name different than they're supposed to access?

Aucun commentaire:

Enregistrer un commentaire