Overriding parent methods with contravariant arguments

Basically, I want to override the parent class with different arguments. For instance:

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

Then override this class, for example:

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, it will return an error Field set overloads parent class with different or incomplete type. Is there any way around this? I tried to use public dynamic functionand then installed setin a function new(), but this gave a very similar error. Any thoughts?

+4
source share
4 answers

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

Here is an example of how it might look:

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;
    }
}

, , , "" , .

+3

. 1 , :

  • T , - , T.
  • . ( ), 2 , (, , ).
  • , . , haxe . ( , - + , , , js/java externs.)
+1

Unfortunately, the language does not allow this.

0
source

If you wrote a base class, you could add an optional argument to it, that would be a workaround, although it’s directly not what you want to do.

0
source

Source: https://habr.com/ru/post/1544992/


All Articles