← Back to Scala Course | Chapter 12: Advanced Features | Lesson 2 of 7

Type Classes Basics

In this page:

  1. Type Classes Basics

Type Classes Basics

A type class is a pattern (not a special keyword) where a trait defines some capability, like Show[T], and separate implicit instances provide that capability for specific types, without modifying those types' original definitions. A generic function then requires an implicit instance of the type class as a parameter to work with any type that has one. This is Scala's flexible alternative to requiring every type to implement a shared interface directly.

Note: Type classes let you add new behavior to existing types (even ones you don't own, like Int) without inheritance or modifying their source.

Example: Type Classes Basics

markup
trait Show[T] {
  def show(value: T): String
}

object Show {
  implicit val intShow: Show[Int] = (value: Int) => s"Int($value)"
  implicit val stringShow: Show[String] = (value: String) => s"Str($value)"
}

object Main extends App {
  def display[T](value: T)(implicit s: Show[T]): Unit = {
    println(s.show(value))
  }

  import Show._
  display(42)
  display("hello")
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.