🔴 Scala Intermediate

What is the type class pattern in Scala?

Answer

The type class pattern enables ad-hoc polymorphism — adding behavior to types without modifying them. It uses Scala's implicit system (Scala 2) or given/using (Scala 3). Define a type class trait: trait Serializable[A] { def serialize(a: A): String }. Provide instances: implicit val intSerializable: Serializable[Int] = new Serializable[Int] { def serialize(n: Int) = n.toString }. Use with an implicit parameter: def print[A](a: A)(implicit s: Serializable[A]) = println(s.serialize(a)). Context bound shorthand: def print[A: Serializable](a: A). Extension methods via implicit class: implicit class SerializableOps[A: Serializable](a: A) { def serialize = implicitly[Serializable[A]].serialize(a) }. This pattern is the foundation of Cats' Functor, Monad, Show, and other abstractions. It allows adding new behavior to existing types without inheritance.