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.
Previous
What is Scala's collections library and its main categories?
Next
What is Akka and what is the actor model?
More Scala Questions
View all →- Intermediate What is Akka and what is the actor model?
- Intermediate What is Apache Spark and how does Scala relate to it?
- Intermediate What is Scala's approach to concurrency with Futures and Promises?
- Intermediate What are Scala's monads and how do they work?
- Intermediate What is Cats library in Scala?