Motif des classes de types
Polymorphisme ad hoc
Motif des classes de types est une leçon Scala for Backend Engineering & Functional Programming gratuite sur CoddyKit. Ceci est la leçon 1 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Scala for Backend Engineering & Functional Programming, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Scala for Backend Engineering & Functional Programming comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
What is a Type Class?
A type class is a pattern for adding behavior to types without modifying them. It is a form of ad-hoc polymorphism: the same operation works for many unrelated types, chosen by the compiler based on type.
It comes from Haskell and is widely used in Scala libraries like Cats.
The Problem It Solves
Inheritance forces behavior into a type at definition time. But you often cannot edit a type (it is in a library), or you want different behaviors in different contexts. Type classes let you attach behavior externally.
Step 1: Define the Trait
A type class is a trait parameterized by a type. Here Show[A] describes how to render any A as a String.
trait Show[A] {
def show(value: A): String
}
@main def run(): Unit = {
println("Show trait defined")
}Step 2: Provide Instances
For each concrete type you want to support, create an instance of the trait. These are the type class instances.
trait Show[A] { def show(value: A): String }
object Main {
val intShow: Show[Int] = (v: Int) => s"Int($v)"
val strShow: Show[String] = (v: String) => s"Str($v)"
def main(args: Array[String]): Unit = {
println(intShow.show(7))
println(strShow.show("hi"))
}
}Step 3: Use the Instance
A function takes the instance as a parameter. The same render function works for any type that has a Show instance.
trait Show[A] { def show(value: A): String }
object Main {
def render[A](value: A, s: Show[A]): String = s.show(value)
val intShow: Show[Int] = (v: Int) => s"<$v>"
def main(args: Array[String]): Unit = {
println(render(99, intShow))
}
}Making It Implicit
Passing instances by hand is tedious. Marking the instance implicit and the parameter implicit (or using in Scala 3) lets the compiler supply it automatically.
trait Show[A] { def show(value: A): String }
object Main {
implicit val intShow: Show[Int] = (v: Int) => s"<$v>"
def render[A](value: A)(implicit s: Show[A]): String = s.show(value)
def main(args: Array[String]): Unit = {
println(render(42))
}
}Ad-hoc Polymorphism
The same function name dispatches to different implementations based on the argument's type. This is ad-hoc polymorphism, distinct from subtype polymorphism (inheritance) and parametric polymorphism (generics).
trait Show[A] { def show(value: A): String }
object Main {
implicit val intShow: Show[Int] = (v: Int) => s"int:$v"
implicit val boolShow: Show[Boolean] = (v: Boolean) => s"bool:$v"
def render[A](value: A)(implicit s: Show[A]): String = s.show(value)
def main(args: Array[String]): Unit = {
println(render(5))
println(render(true))
}
}Working with Custom Types
The real power: add behavior to your own types cleanly, keeping the data class free of formatting concerns.
trait Show[A] { def show(value: A): String }
case class User(name: String, age: Int)
object Main {
implicit val userShow: Show[User] = (u: User) => s"${u.name} (${u.age})"
def render[A](value: A)(implicit s: Show[A]): String = s.show(value)
def main(args: Array[String]): Unit = {
println(render(User("Ada", 36)))
}
}Type Classes vs Interfaces
An interface couples behavior to the type's definition; a type class decouples them.
- You can add a type class instance for a type you do not own.
- You can have multiple instances for different contexts.
- Behavior is selected at the call site by the compiler.
Three Components
Every type class has three parts:
- The trait (the abstract operation).
- The instances (implementations per type).
- The interface (functions that require an instance).
You will explore each in the following lessons.
A Complete Mini Example
Tying the pattern together with a generic function that uses an implicit instance.
trait Show[A] { def show(value: A): String }
object Main {
implicit val intShow: Show[Int] = (v: Int) => s"#$v"
implicit val strShow: Show[String] = (v: String) => '"' + v + '"'
def printAll[A](xs: List[A])(implicit s: Show[A]): Unit =
xs.foreach(x => println(s.show(x)))
def main(args: Array[String]): Unit = {
printAll(List(1, 2, 3))
printAll(List("a", "b"))
}
}Quick Check
Test your grasp of the type class pattern.
Recap
You learned the type class pattern:
- A parameterized
traitdescribes an operation. - Instances implement it per type.
implicitparameters let the compiler supply the instance.- This gives ad-hoc polymorphism and lets you extend types you do not own.
Questions Fréquemment Posées
La leçon « Motif des classes de types » est-elle gratuite ?
Oui — le texte complet de « Motif des classes de types » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Scala for Backend Engineering & Functional Programming, passe à CoddyKit PRO. Le cours Scala for Backend Engineering & Functional Programming comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Motif des classes de types » ?
Polymorphisme ad hoc Tu pratiques Scala for Backend Engineering & Functional Programming avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Scala for Backend Engineering & Functional Programming ?
Aucune expérience préalable n'est requise. Scala for Backend Engineering & Functional Programming sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 1 sur 4.
Combien de temps prend la leçon « Motif des classes de types » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Scala for Backend Engineering & Functional Programming ?
Oui. Chaque leçon Scala for Backend Engineering & Functional Programming inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Motif des classes de types
- Définir des instances
- Classes de types courantes
- Dérivation des classes de types