archives

Different approaches to letting a programmer define interface implementations.

I'm looking at how different statically typed languages tackle the problem of letting you define types and define interface implementations for those types.

For example, to define an implementation of interface I for type T, Java uses interface methods, Haskell uses typeclasses, Scala uses implicits.

The disadvantage of the Java approach when compared with Haskell/Scala:

  • You need a value of type T to call the method.
  • equals() isn't symmetric.
  • Must implement interface for T in the same module as T. This is probably not much of a problem for equality/ordering/hashing, but can be problematic for interfaces that aren't part of the core library.

Haskell approach vs Scala approach:

  • Haskell only allows one interface implementation per type, whereas Scala lets the programmer specify the implementation explicitly at the constraint site, if necessary. I can see arguments for both.
  • Scala's implicits allow more simple overriding. I don't see why you'd want to override equality/ordering, but maybe redefining hashing could be useful?

What do you think is the "right" way to do this? Given my limited knowledge right now, I think I'd go with something Scala-like and maybe make some modifications. For example, I think the "only one implementation per type" restriction of Haskell might be useful.

Is there a good survey of the different approaches?