Scala Reactive Programming
上QQ阅读APP看书,第一时间看更新

Scala Type class

In Scala, a Type class defines some behavior in terms of some operations. If a new class (or Type) wants to join as a member of that Type class, it must provide implementation to all operations, which are defined in that Type class.

So in simple words, a Type class is a group of classes which provides implementation to a contract (or an interface).

The main goal of Type classes is to define a contract or interface to its types.

Unlike sub-type polymorphism, which uses OOP inheritance, Type classes follow ad hoc polymorphism, using composition and support DRY (Do NOT Repeat Yourself) and SRP (Single Responsibility Principle).

Like generics or Type parameters, Type classes are resolved at compile time. The following diagram shows the main goal of  Scala Type class:

Types of polymorphism in brief:

  • Parametric polymorphism—using generics:
      trait Json[T] 
  • Sub-type polymorphism:
      trait Json 
       object StringJson extends Json 
  • Ad-hoc polymorphism—it is overloading:
      trait Json[T] 
       object StringJson extends Json[String] 

The preceding two examples just demonstrate how to use implicits. However, in our real-time projects we should never use these kinds of common types as implicits.