Search code examples
interfaceargumentshaxe

Haxe: Function argument that matches an interface


I have a method (in Haxe) that needs to accept any object that has a 'width' and 'height' property. I'm assuming that I can do that somehow with an Interface, but for my purposes the object that is passed in does not need to implement the interface, it just needs to be any object with a width and height property.

This does not work, as the object you pass in needs to implement interface:

Interface IWidthAndHeight{
    public var width : Float;
    public var height : Float;
}

Class Main{

    var o : IWidthAndHeight;

    public function setObject( o : IWidthAndHeight ){
        this.o = o;
    }

}

Currently I am using Dynamic, and manually cheking that the properties exist, but is there a smarter way? Current method:

Class Main{

    var o : Dynamic;

    public function setObject( o : Dynamic ){
        if (propertiesExist(o,['width','height'])){
            this.o = o;
        }
    }

    // Note: propertiesExist is my own method. Just assume it works :)
}

Any help appreciated. Thanks!


Solution

  • You can use anonymous structures here:

    typedef WidthAndHeight = {
        width:Float,
        height:Float
    }
    class Main {
        var o:WidthAndHeight;
        public function setObject(o:WidthAndHeight) {
            this.o = o;
        }
    }
    

    This is just alternative to var o:{width:Float, height:Float}; with typedef. Any class or structure in setObject argument will be checked for these fields in compile time, this is called structural subtyping.