Full Haskell-like Type Class resolution in Java
The post describes building a Haskell-style type class[1] instance resolution engine entirely in plain Java, using only reflection, generic type metadata, and a small first-order unification[2] implementation. The engine automatically resolves type class instances, including higher-kinded ones, supports overlapping instances, and derives witnesses[3] for arbitrarily nested generic types. It is not intended for production; as an experiment it shows how much structure Java preserves at runtime and how close it can get to type-level programming without language changes, and the full implementation is available in a gist and in the GitHub repo github.com/garciat/java-type-classes.
The motivating problem: a record Dup<A> implementing Equatable<Dup<A>> cannot call eq() on its A components without the bound A extends Equatable<A>, which makes Dup compatible only with types that extend Equatable, and runtime instanceof checks work poorly with generics and can fail. The type class pattern moves equality to the type itself: the Eq<A> interface compares two values, Point stops implementing the interface and exposes a static Eq<Point> witness constructor, and Dup's constructor takes an Eq<A> parameter to build Eq<Dup<A>>. Witnesses compose: mapEq(stringEq(), listEq(integerEq())) builds Eq<Map<String, List<Integer>>>. The author takes the term "witness" from Brian Goetz, Java's architect, who used it in a recent talk about bringing type classes to Java in the future.
The rest of the post works toward automatic witness construction, so a witness() method can build, for example, Show<List<List<Integer>>> instead of manually chained calls like Show.showList(Show.showList(Show.showInteger())). Java normally applies type erasure[4] to generics at runtime, but type arguments are reified in certain places: getGenericInterfaces() returns Stream<Integer> for IntStream, anonymous classes keep their arguments, so an anonymous subclass of a helper interface Ty<T> exposes its type argument as a java.lang.reflect.Type. The post then walks through the java.lang.reflect.Type hierarchy — Class, GenericArrayType, ParameterizedType, TypeVariable, WildcardType — and how Method exposes type parameters, generic parameter types and the generic return type, as groundwork for the resolution engine.
Read the original garciat.comDiscussion
Sources
-
garciat.com
Full Haskell-like Type Class resolution in Java


