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:
Syntax
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
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")
}
Login to try C/C++/Java/PHP code in the editor
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
- Forgetting to put the implicit instance in scope, so the call fails with
could not find implicit value for parameter. - Defining the instance for the wrong type, such as
Show[Long]when the call usesInt. - 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: