Either pour les erreurs
Left et Right
Either pour les erreurs 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.
Why Either?
Either represents a value that can be one of two possibilities. It is the idiomatic way to model computations that may fail with information about the failure.
Leftconventionally holds the error.Rightconventionally holds the success value.
Unlike Option, which only tells you something is missing, Either tells you what went wrong.
The Either Type
Either[A, B] is a sealed trait with two subtypes: Left[A] and Right[B].
The mnemonic: Right is right (correct), Left is the error. This convention lets map and flatMap operate on the success side automatically.
val ok: Either[String, Int] = Right(42)
val err: Either[String, Int] = Left("boom")
println(ok)
println(err)Returning Either from a Function
A function that can fail returns an Either instead of throwing. The caller can then handle both outcomes explicitly.
object Main {
def parseAge(s: String): Either[String, Int] =
s.toIntOption match {
case Some(n) if n >= 0 => Right(n)
case Some(_) => Left("age cannot be negative")
case None => Left("not a number")
}
def main(args: Array[String]): Unit = {
println(parseAge("30"))
println(parseAge("-5"))
println(parseAge("x"))
}
}Pattern Matching on Either
The most direct way to consume an Either is pattern matching. You handle Left and Right separately.
@main def run(): Unit = {
val result: Either[String, Int] = Right(10)
val msg = result match {
case Right(value) => s"Got value: $value"
case Left(error) => s"Failed: $error"
}
println(msg)
}fold: Collapse Both Sides
fold takes two functions: one for Left and one for Right, and produces a single result of a common type.
It is a concise alternative to pattern matching when you want a value back.
@main def run(): Unit = {
val r: Either[String, Int] = Right(7)
val label = r.fold(
err => s"error: $err",
num => s"double is ${num * 2}"
)
println(label)
}map Works on the Right
map transforms the Right value and leaves a Left untouched. This is the right-biased behavior of Scala's Either (since 2.12).
@main def run(): Unit = {
val ok: Either[String, Int] = Right(5)
val no: Either[String, Int] = Left("missing")
println(ok.map(_ + 1))
println(no.map(_ + 1))
}getOrElse and Defaults
getOrElse extracts the Right value or returns a fallback when the Either is a Left.
@main def run(): Unit = {
val ok: Either[String, Int] = Right(99)
val no: Either[String, Int] = Left("oops")
println(ok.getOrElse(0))
println(no.getOrElse(0))
}swap: Flip the Sides
swap exchanges Left and Right. This is handy when you want to operate on the error side using right-biased methods.
@main def run(): Unit = {
val err: Either[String, Int] = Left("bad input")
val swapped = err.swap.map(_.toUpperCase)
println(swapped)
}isLeft and isRight
Quick boolean checks let you branch without full pattern matching.
isRightreturns true for a success.isLeftreturns true for an error.
@main def run(): Unit = {
val r: Either[String, Int] = Right(1)
println(r.isRight)
println(r.isLeft)
}toOption: Discard the Error
When you no longer care why something failed, toOption converts an Either into an Option: Right(x) becomes Some(x) and Left(_) becomes None.
@main def run(): Unit = {
val ok: Either[String, Int] = Right(3)
val no: Either[String, Int] = Left("err")
println(ok.toOption)
println(no.toOption)
}A Validation Example
Putting it together: validate a username, returning a typed error on failure.
object Main {
def validate(name: String): Either[String, String] =
if (name.isEmpty) Left("empty name")
else if (name.length > 10) Left("name too long")
else Right(name)
def main(args: Array[String]): Unit = {
println(validate("alice"))
println(validate(""))
println(validate("verylongusername"))
}
}Quick Check
Test your understanding of Either conventions.
Recap
You learned to model errors with Either:
Right= success,Left= error (right-biased).- Consume with pattern matching or
fold. - Transform the success with
map; provide defaults withgetOrElse. - Flip sides with
swap; convert withtoOption.
Next, you will handle exceptions with Try.
Questions Fréquemment Posées
La leçon « Either pour les erreurs » est-elle gratuite ?
Oui — le texte complet de « Either pour les erreurs » 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 « Either pour les erreurs » ?
Left et Right 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 « Either pour les erreurs » ?
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
- Either pour les erreurs
- Try, Success, Failure
- Composer Either
- Convertir entre les types