I am working with Java of late, and was wondering whether there was any kind of interface implementation derivation in Java. My preferred programming language is Haskell, which is in many ways antithetical to Java, but one feature that I was wondering whether Java had anything like is the ability to derive interface implementations of compound types from the interface implementations of their parameters. For example, in Haskell:
data Pair k v = Pair k v
instance (Ord k) => Ord (Pair k v) where
compare (Pair x _) (Pair x' _) = compare x x'
This allows you to order a Pair
if its first parameter can be ordered, without explicitly requiring that to be the case. However, the closest I can come to this in Java is through explicit requirement:
class Pair<K extends Comparable<K>, V> extends Comparable<Pair<K,V>> {
K k;
V v;
public int compareTo(Pair<K,V> p) {
return k.compareTo(p.k);
}
}
Without a way of leaving the comparability to be inferred, it is impossible for me to implement a BST of pairs without ensuring that all pairs have a comparable first element, so I cannot implement any kind of Map where the first element is not explicitly required to be Comparable. Is there any way around this, other than creating a method of my BST class that attempts to compare the generic type by casting it first as comparable, and then as a Pair with a comparable key, comparing whenever comparability is possible?