Éviter null
Bases de Option
Éviter null 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.
The Problem With null
In many languages, a missing value is represented by null. But null causes the dreaded NullPointerException when you forget to check it.
Scala offers a safer alternative: the Option type.
What Is Option?
Option[A] represents a value that may or may not be present. It has exactly two cases:
Some(value)when a value existsNonewhen there is no value
The type itself tells you a value might be missing.
object Main {
def main(args: Array[String]): Unit = {
val present: Option[Int] = Some(42)
val absent: Option[Int] = None
println(present)
println(absent)
}
}Creating Some
Wrap an existing value in Some to say it is definitely present.
object Main {
def main(args: Array[String]): Unit = {
val name: Option[String] = Some("Ada")
println(name)
}
}Representing Absence With None
None is the single value used when nothing is there. It works for any Option type.
object Main {
def lookup(found: Boolean): Option[Int] =
if (found) Some(100) else None
def main(args: Array[String]): Unit = {
println(lookup(true))
println(lookup(false))
}
}Functions That May Fail
Returning Option makes the possibility of no result explicit in the type signature. Callers cannot ignore it.
object Main {
def findUser(id: Int): Option[String] =
if (id == 1) Some("Grace") else None
def main(args: Array[String]): Unit = {
println(findUser(1))
println(findUser(2))
}
}Checking With isDefined and isEmpty
isDefined tells you if an Option is a Some, and isEmpty tells you if it is None.
object Main {
def main(args: Array[String]): Unit = {
val a: Option[Int] = Some(5)
val b: Option[Int] = None
println(a.isDefined)
println(b.isEmpty)
}
}Pattern Matching an Option
Because Option is a sealed ADT, you can pattern match on it. This handles both presence and absence clearly.
object Main {
def greet(name: Option[String]): String = name match {
case Some(n) => s"Hello, $n"
case None => "Hello, stranger"
}
def main(args: Array[String]): Unit = {
println(greet(Some("Bo")))
println(greet(None))
}
}Option From Nullable Values
If you must work with code that returns null, wrap it with Option(...). It converts null to None and any real value to Some.
object Main {
def main(args: Array[String]): Unit = {
val maybe = Option("data")
val nothing = Option(null)
println(maybe)
println(nothing)
}
}Standard Library Returns Option
Many built-in methods already return Option instead of risking errors. For example, List.headOption safely handles empty lists.
object Main {
def main(args: Array[String]): Unit = {
val xs = List(1, 2, 3)
val empty = List.empty[Int]
println(xs.headOption)
println(empty.headOption)
}
}Why Option Over null?
Option beats null because it:
- Makes missing values visible in the type
- Forces callers to handle the absent case
- Eliminates NullPointerExceptions
- Composes with map, flatMap, and for-comprehensions
Putting It Together
A small lookup that returns Option, then is safely handled with pattern matching.
object Main {
val prices = Map("apple" -> 3, "pear" -> 5)
def priceOf(item: String): Option[Int] = prices.get(item)
def main(args: Array[String]): Unit = {
priceOf("apple") match {
case Some(p) => println(s"costs $p")
case None => println("not for sale")
}
println(priceOf("banana"))
}
}Quick Check
Test your understanding of Option.
Recap
You learned to avoid null with Option:
Option[A]isSome(value)orNone- It makes possible absence explicit in the type
- Check with
isDefined/isEmptyor pattern match - Use
Option(x)to wrap nullable values - Library methods like
headOptionandMap.getreturn Option
Questions Fréquemment Posées
La leçon « Éviter null » est-elle gratuite ?
Oui — le texte complet de « Éviter null » 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 « Éviter null » ?
Bases de Option 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 « Éviter null » ?
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.