Is it possible to return "this" in generic interface with default implement using f-bounded quantification

147 Views Asked by At
public interface IEq<T> {
  public abstract Boolean testEqual(final T y);

  public default Boolean testNotEqual(final T y) {
    return !this.testEqual(y);
  }
}

public interface IOrd<T> extends IEq<T> {
  public abstract Boolean lessEqualThan(final T y);

  public default T min(final T y) {
    if(lessEqualThan(y)) return this; // <--- ERROR: cannot convert from IOrd<T> to T
    else return y;
  }
}    

This OOP style code is very simlilar with https://en.wikipedia.org/wiki/Bounded_quantification.

The difference is I move the external function (Fmin) to Object method (min)

My question is: Is it possible to return "this" in the generic interface (IOrd) with default implement (min: T -> T) using f-bounded quantification?

1

There are 1 best solutions below

0
On

You can't return IOrd<T> in a method which return T. You have to change your signature:

public abstract Boolean lessEqualThan(final IOrd<T> y);


public default IOrd<T> min(final IOrd<T> y) {
    if(lessEqualThan(y)) return this;
    else return y;
}

If you want to return T you must provide a way to get the T value from your implementation class:

public abstract Boolean lessEqualThan(final T y);

T getTValue(); // Your implementation must provide a way to get the T value

public default T min(final T y) {
    if(lessEqualThan(y)) return getTValue();
    else return y;
}