0

In this interface, I have default implementations:

public interface Arithmeticable<T extends AlgebraicInteger> {
    
    T plus(T addend);
    
    T plus(int addend);
    
    default T negate() {
        return this.times(-1);
    }
    
    T minus(T subtrahend);
    
    default T minus(int subtrahend) {
        return this.plus(-subtrahend);
    }
    
    T times(T multiplicand);
    
    T times(int multiplicand);
    
    T divides(T divisor) throws NotDivisibleException;
    // may also throw a runtime exception for division by 0
    
    T divides(int divisor) throws NotDivisibleException;
    // may also throw a runtime exception for division by 0
    
}

Naturally, one would think there is one more default implementation to be had here:

    default T minus(T subtrahend) {
        return this.plus(subtrahend.negate());
    }

But the problem is that the compiler doesn't know negate() can be called on subtrahend. In fact it's a human assumption that T implements Arithmeticable<T>. It could just as easily be implemented by a class other than T.

The only thing we can count on T to have is what Object and AlgebraicInteger define. Is there a way to require T to implement Arithmeticable<T>?

I have this vague memory of doing something like this in Scala. Can it be done in Java?

Alonso del Arte
  • 1,005
  • 1
  • 8
  • 19
  • 1
    How did you define `AlgebraicInteger`? Can that interface include the `negate` method? – Thilo Oct 03 '20 at 00:15
  • What is the difference between `AlgebraicInteger` and `Arithmeticable`, why are these two separate types? – Thilo Oct 03 '20 at 00:17
  • @Thilo Like this: https://github.com/Alonso-del-Arte/algebraic-integer-calculator/blob/master/code-source/algebraics/AlgebraicInteger.java Yes, `AlgebraicInteger` could include `Arithmeticable`. It wouldn't be terribly SOLID, but it would be a valid answer to this question. – Alonso del Arte Oct 03 '20 at 00:19
  • 2
    For your last question, you can say `>` https://stackoverflow.com/q/745756/14955 – Thilo Oct 03 '20 at 00:19
  • @Thilo "why are these two separate types?" Honestly, it's mostly because I haven't figured out arithmetic beyond the quadratics. – Alonso del Arte Oct 03 '20 at 00:26

0 Answers0