Java’s Interface and Haskell’s type class: differences and similarities?

I would say that an interface is kind of like a type class SomeInterface t where all of the values have the type t -> whatever (where whatever does not contain t). This is because with the kind of inheritance relationship in Java and similar languages, the method called depends on the type of object they are called on, and nothing else.

That means it’s really hard to make things like add :: t -> t -> t with an interface, where it is polymorphic on more than one parameter, because there’s no way for the interface to specify that the argument type and return type of the method is the same type as the type of the object it is called on (i.e. the “self” type). With Generics, there are kinda ways to fake this by making an interface with generic parameter that is expected to be the same type as the object itself, like how Comparable<T> does it, where you are expected to use Foo implements Comparable<Foo> so that the compareTo(T otherobject) kind of has type t -> t -> Ordering. But that still requires the programmer to follow this rule, and also causes headaches when people want to make a function that uses this interface, they have to have recursive generic type parameters.

Also, you won’t have things like empty :: t because you’re not calling a function here, so it isn’t a method.

Leave a Comment