[Haskell-beginners] Type classes vs Java interfaces

Bryan Vicknair bryanvick at gmail.com
Fri Feb 1 15:45:56 CET 2013

On Feb 1, 2013, at 5:25 AM, Bob Hutchison <hutch-lists at recursive.ca> wrote:

> On 2013-01-31, at 6:36 PM, Mateusz Kowalczyk <fuuzetsu at fuuzetsu.co.uk> wrote:
>> Greetings,
>> I often wonder how one would explain type classes to someone coming from
>> an environment such as Java. Whenever I think about type classes, I seem
>> to think of them as Java interfaces. Bah, even the bottom of [1] states
>>> Haskell classes are roughly similar to a Java interface. Like an
>> interface declaration, a Haskell class declaration defines a protocol
>> for using an object rather than defining an object itself.
>> Is there more to this `roughly similar' statement? Syntax is an obvious
>> difference but beyond that, I can't think of anything I can do with a
>> Haskell type class that I wouldn't be able to do with similar amount of
>> effort with a Java interface, except for the fact that the interface
>> would look absolutely disgusting syntax wise.
>> Any insight appreciated.
> Well I have limited insight but…
> Type classes can provide default implementations, which is not possible in Java.
> Type classes in a type signature describe or constrain a type and but are not themselves types. Among other things, this means in Haskell that collections must be homogeneous in their actual type, it's not sufficient to be "homogeneous in a type class". There are extensions to GHC that make this possible [1] but there are limitations and the usage has its detractors [2]. In Java you can have collections of objects that conform to a given interface even if they are of different classes. Personally, I find Haskell's restriction counter-intuitive but the sense of surprise and  limitation is diminishing as I use the language.

As I understand them, typeclasses allow you to add a type to a class without modifying the type definition at all, so they are more flexible than Java interfaces in that way.

I don't do much java, but I don't think you can define a class' implementation of an interface outside of the class.  In Haskell, I can define a typeclass that suites my domain, and add another author's type as an instance, and the author doesn't have to know about it.

Bryan Vicknair

More information about the Beginners mailing list