[Haskell-beginners] Type classes vs Java interfaces

Bob Hutchison hutch-lists at recursive.ca
Fri Feb 1 14:25:43 CET 2013

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.


[1] -- http://www.haskell.org/haskellwiki/Heterogenous_collections#Existential_types
[2] -- https://lukepalmer.wordpress.com/2010/01/24/haskell-antipattern-existential-typeclass/

> [1] - http://www.haskell.org/tutorial/classes.html
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners

More information about the Beginners mailing list