Type Class, a Scala language concept
Last updated
Type classes are one of Scala's most important super-powers: they enable you to add new behaviour to existing classes, without modifying those classes. In many languages, to add a behaviour to a class, you would typically extend it with an interface, and then implement methods against this interface.This, however, does not scale: especially when you have older libraries, you would be forced to make them depend on a new interface, and have to re-build everything.
Type classes are used heavily in Apple's SwiftUI as "extensions" to enable powerful abstraction capabilities.
Key points:
- You can add new behaviour to pre-existing classes.
- You can re-use generic behaviour on new classes.
These possibilities are enhanced with syntatic sugar that enables you to develop extremely concise code, and we will demonstrate this here.
Type classes normally are enhanced with syntatic sugar to save the amount of typing:
And finally, we can re-use generically implemented behaviour on new classes, by simply declaring a new 'instance' of a type class!
Background
Type classes are a concept inspired by those in Haskell.
Their use massively extends what you can do with Scala, and they are widely used in libraries like 'cats'.
Another worthwhile example of type classes
To see more of Ordering, go to Ordering.