Jim Gordowsky
Jim Gordowsky

Reputation: 181

What is the naming convention for typeclasses in Scala?

In Java world, the naming conventions for interfaces are pretty much well established. For instance, when you say certain class implements the interface Comparable, you can say that it's objects are comparable. However the naming conventions for typeclasses are not so well established. For example, Int has a Numeric implicit available, so you can say "Int is a Numeric type". But then there is typeclass Ordering. I fail to see why this name was chosen. "Int is an Ordering type" doesn't make any sense. Perhaps it is supposed to be read as "Int type has an Ordering". Then there are Equal and Show in Scalaz. I totally have no idea why these names were chosen (apart from that they are so in Haskell.) I tried looking at Haskell, the mother language of typeclasses, for a good naming convention but found that there doesn't really exist any. Haskell guys don't really seem to care about names (That's what I gathered from the mailing list discussions). But coming from Java world, I do care about names. I am not quite able to get accustomed to "types say it all" paradigm.

The question is: What naming conventions do you follow, if at all you do, for naming the typeclasses?

Upvotes: 18

Views: 1636

Answers (1)

C. A. McCann
C. A. McCann

Reputation: 77374

Actually, things are mostly straightforward in Haskell: Type classes are typically named based on what the operations represent, not what the type parameter represents.

For example:

  • Read, Show: Classes of types for which standard string serialization/deserialization functions are defined.
  • Eq, Ord: Classes of types on which equality and ordering relations, respectively, are defined.
  • Enum: The class of types defining a "successor" operation, i.e., whose values can be enumerated.
  • Monoid, Functor, Monad: Classes of types which define the operations associated with the similarly-named mathematical structures.

Some examples aren't so good: For instance, Num is a class of types on which an ad-hoc collection of vaguely-arithmetic-oriented operations are defined, but there's no reason that an instance of Num must actually be a number in any conventional sense. This could perhaps be handwaved as "types supporting numeric operations", pretending that "numeric" actually means anything in that phrase.

In short, Numeric is probably a bad example to imitate, and if a type class has only one function (possibly with multiple variants on it), it's almost always safe to name the class after that function, as with show vs. Show.

But really, the main thing is to think in terms of the functions on the type class, not the type parameter. Think verbs, not nouns. Nouns are dumb inert things anyway, so thinking in terms of actions and operations is likely to lead to better program design.

Upvotes: 26

Related Questions