In Haskell (and Rust, and others) I can have instances that are constrained by other instances:
data Pair a b = Pair a b
instance (Eq a, Eq b) => Eq (Pair a b) where
Pair a b == Pair a' b' = a == a' && b == b'
With Java interfaces I can't. I must require the type parameters of Pair
to always implement Eq
, or I can't implement Eq<Pair<A, B>>
at all:
interface Eq<A> {
public boolean eq(A other);
}
class Pair<A extends Eq<A>, B extends Eq<B>> implements Eq<Pair<A, B>> {
A a;
B b;
public boolean eq(Pair<A, B> other){
return a.eq(other.a) && b.eq(other.b);
}
}
I'd like to have something like:
class Pair<A, B> implements Eq<Pair<A, B>> if (A implements Eq<A> && B implements Eq<B>) {...}
So far the Internet has told me that my desired functionality isn't directly supported in Java. Nevertheless I find this a rather critical factor in the (re)usability of interfaces. I'd like to know if there are workarounds or solutions that approximately cover the same ground.