Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding parent methods with contravariant arguments

Tags:

haxe

Basically, I want to override a parent class with different arguments. For example:

class Hold<T> {
    public var value:T;
    public function new(value:T) {
        set(value);
    }
    public function set(value:T) {
        this.value = value;
    }
}

Then override that class, something like:

class HoldMore extends Hold<T> {
    public var value2:T;
    public function new(value:T, value2:T) {
        super(value);
        set(value, value2);
    }
    override public function set(value:T, value2:T) {
        this.value = value;
        this.value2 = value2;
    }
}

Obviously this will return an error, Field set overloads parent class with different or incomplete type. Is there a way around this? I tried using a public dynamic function, and then setting set in the new() function, but that gave a very similar error. Any thoughts?

like image 320
steve richey Avatar asked Jun 17 '14 21:06

steve richey


2 Answers

This is just a complement to @stroncium's answer, which is totally correct.

Here is an example how it could look like:

class Hold<T> {
    public var value:T;
    public function new(value:T) {
        set(value);
    }
    public function set(value:T) {
        this.value = value;
    }
}

class HoldMore<T> extends Hold<T> {
    public var value2:T;
    public function new(value:T, value2:T) {
        super(value);
        setBoth(value, value2);
    }
    // you cannot override "set" with a different signature
    public function setBoth(value:T, value2:T) {
        this.value = value;
        this.value2 = value2;
    }
}

alternatively, you could use an array as parameter or a dynamic object holding multiple values in order to "set" them using the same method, but you loose some of the compiler's type checking.

like image 90
dagnelies Avatar answered Sep 20 '22 02:09

dagnelies


If you wrote the base class you could add an optional argument to it, this would be a workaround though, not directly what you want to do.

like image 30
npretto Avatar answered Sep 21 '22 02:09

npretto