Search code examples
actionscript-3setterhaxegetteropenfl

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?


Solution

  • Sorry, it was me who was missing something. The way getters and setters are properly defined in Haxe Now, after I've seen the example by Ben Morris here, I got the point. So besides width and height properties I had some custom ones to override and they gave me "missing physical field errors" I just had to specify a physical field for them and then use any properties in get_ / set_ accessors E.g.

    // physical field
    public var top(get, set):Float;
    var _customTop:Float = 100;
    
    public function get_top():Float {
        return _customTop; // now I can return what ever here
    }
    public function set_top(value:Float):Float{
        return _customTop = value; 
    }
    

    I don't know who has downvoted my question, but this is really crucial matter I've spent a lot of time trying to get the solution for. And it was really so easy. Thanks to Ben Morris! If you had posted your comment as answer, I would accept it