Explain the use of type classes in Scala for ad-hoc polymorphism.

Instruction: Discuss how type classes enable ad-hoc polymorphism in Scala, including examples.

Context: This question is intended to assess the candidate's understanding of ad-hoc polymorphism through type classes in Scala, illustrating the concept with practical examples.

Updated

A type class separates a capability from the data type receiving it. A generic function asks for an instance such as Render[A]; different instances provide behavior for different types without requiring those data types to inherit a common domain superclass.

trait Display[A] { def text(value: A): String }
object Display {
  given Display[Int] with {
    def text(value: Int): String = value.toString
  }
  given Display[String] with {
    def text(value: String): String = value
  }
}
final case class Ticket(number: Int)
object Ticket {
  given Display[Ticket] with {
    def text(value: Ticket): String = s"ticket-${value.number}"
  }
}
def display[A](value: A)(using instance: Display[A]): String =
  instance.text(value)

@main def typeClassExample(): Unit = {
  assert(display(12) == "12")
  assert(display("quoted: \"x\"") == "quoted: \"x\"")
  assert(display(Ticket(7)) == "ticket-7")
}

The compiler resolves the contextual argument at the call site. The selected instance is an ordinary value used by the function; this is distinct from overriding a method on the input object. An explicit using argument can select a different policy, and a missing or ambiguous instance causes a compilation error. Context bounds provide shorthand when appropriate. Scala 3 type classes

This example produces display text, not JSON. Surrounding an arbitrary string with quotation marks is not a correct JSON encoder: quotes, backslashes and control characters require escaping. Use a maintained JSON library and its tested encoder type class when JSON is the actual requirement.

Type classes allow behavior for types whose source code you do not own, but instance placement and imports need care to avoid conflicting policies. The compiler checks types and availability, not semantic laws, escaping correctness, determinism or performance. Test each instance against the capability's contract.

Related Questions