0Pricing
Scala for Backend Engineering & Functional Programming · Leçon

Classes de types de Cats

Functor, Monad, etc.

Classes de types de Cats 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 Are Type Classes?

A type class is a pattern for ad-hoc polymorphism. It lets you add behavior to a type without modifying it. Cats is a Scala library that provides a rich hierarchy of type classes for functional programming.

  • Functor — things you can map over
  • Applicative — combine independent effects
  • Monad — sequence dependent effects

Functor: map

A Functor[F] provides map. It transforms the value inside a context without changing the context's structure.

import cats.Functor
import cats.instances.option._

val f = Functor[Option].map(Some(2))(_ + 1)
println(f) // Some(3)

Functor Laws

A lawful Functor must obey two laws:

  • Identity: fa.map(x => x) == fa
  • Composition: fa.map(f).map(g) == fa.map(f.andThen(g))

These guarantees let you refactor map chains safely.

Applicative: pure and ap

Applicative[F] extends Functor and adds pure (lift a value into the context) and the ability to combine independent values with mapN.

import cats.Applicative
import cats.instances.option._

val lifted = Applicative[Option].pure(42)
println(lifted) // Some(42)

Combining with mapN

The mapN syntax combines several independent effectful values into one, applying a function once all are present.

import cats.syntax.apply._
import cats.instances.option._

val result = (Option(1), Option(2), Option(3)).mapN(_ + _ + _)
println(result) // Some(6)

Monad: flatMap

Monad[F] extends Applicative and adds flatMap, which sequences dependent computations. Each step can depend on the result of the previous one.

import cats.Monad
import cats.instances.option._

val m = Monad[Option].flatMap(Some(3))(x => Some(x * 10))
println(m) // Some(30)

Monad Laws

Monads must obey three laws:

  • Left identity: pure(a).flatMap(f) == f(a)
  • Right identity: m.flatMap(pure) == m
  • Associativity: nested flatMaps can be re-grouped

Semigroup and Monoid

A Semigroup[A] defines combine (associative). A Monoid[A] adds an empty identity element. These power folding and accumulation.

import cats.syntax.semigroup._
import cats.instances.int._
import cats.instances.string._

println(3 |+| 4)       // 7
println("foo" |+| "bar") // foobar

Foldable

Foldable[F] abstracts folding over a structure. Combined with Monoid, combineAll reduces a collection to a single value.

import cats.Foldable
import cats.instances.list._
import cats.instances.int._

val total = Foldable[List].combineAll(List(1, 2, 3, 4))
println(total) // 10

Traverse

Traverse[F] lets you map each element to an effect and collect the results, turning List[F[A]] into F[List[A]].

import cats.syntax.traverse._
import cats.instances.list._
import cats.instances.option._

val r = List(1, 2, 3).traverse(x => Option(x * 2))
println(r) // Some(List(2, 4, 6))

Why Type Classes Matter

Type classes let you write code that works for any type providing the required behavior. A function constrained by Monad[F] works for Option, List, IO, and more — write once, reuse everywhere.

import cats.Monad
import cats.syntax.flatMap._
import cats.syntax.functor._

def twice[F[_]: Monad, A](fa: F[A])(f: A => A): F[A] =
  fa.flatMap(a => Monad[F].pure(f(f(a))))

Quick Check

Which type class adds flatMap for sequencing dependent computations?

Recap

You explored the core Cats type class hierarchy:

  • Functor — map
  • Applicative — pure and mapN
  • Monad — flatMap
  • Semigroup/Monoid — combine/empty
  • Foldable/Traverse — fold and collect effects

Next you'll meet the IO monad to model effects purely.

Questions Fréquemment Posées

La leçon « Classes de types de Cats » est-elle gratuite ?

Oui — le texte complet de « Classes de types de Cats » 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 « Classes de types de Cats » ?

Functor, Monad, etc. 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 « Classes de types de Cats » ?

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

  1. Classes de types de Cats
  2. La monade IO
  3. Composer IO
  4. Gestion des erreurs dans IO
← Retour à Scala for Backend Engineering & Functional Programming