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

Type Classes Basics

A type class is a pattern for adding a new ability to types without changing them, like giving many different animals the same trick card. Code then works for any type that has the card.

In this page:

  1. Type Classes Basics
Syntax
scala
trait TypeClass[T] {
  def operation(value: T): ReturnType
}

implicit val instance: TypeClass[Type] = new TypeClass[Type] {
  def operation(value: Type): ReturnType = expression
}

def function_name[T](value: T)(implicit tc: TypeClass[T]) = tc.operation(value)

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")
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting to put the implicit instance in scope, so the call fails with could not find implicit value for parameter.
  2. Defining the instance for the wrong type, such as Show[Long] when the call uses Int.
  3. Confusing a type class with inheritance, when a type class adds behaviour to existing types without changing them.
🔒

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.