map y flatMap sobre Option
Componga de forma segura
map y flatMap sobre Option es una lección gratuita de Scala for Backend Engineering & Functional Programming en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Scala for Backend Engineering & Functional Programming, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Scala for Backend Engineering & Functional Programming incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Transforming an Option
Often you have an Option and want to transform the value if it is present, leaving None untouched.
The map method does exactly this, without unwrapping by hand.
Using map
map applies a function to the value inside a Some and returns a new Some. On None it does nothing and returns None.
object Main {
def main(args: Array[String]): Unit = {
val n: Option[Int] = Some(10)
val doubled = n.map(x => x * 2)
println(doubled)
}
}map on None
When the Option is None, map skips the function entirely and stays None.
This is the key safety property: transformations are no-ops on absence.
object Main {
def main(args: Array[String]): Unit = {
val empty: Option[Int] = None
val result = empty.map(x => x * 2)
println(result)
}
}Changing the Type
map can transform to a different type, just like on collections. Here an Option[Int] becomes an Option[String].
object Main {
def main(args: Array[String]): Unit = {
val n: Option[Int] = Some(7)
val label = n.map(x => s"value=$x")
println(label)
}
}The Nesting Problem
What if your function itself returns an Option? Using map would give you a nested Option[Option[A]], which is awkward.
That is where flatMap comes in.
object Main {
def half(x: Int): Option[Int] = if (x % 2 == 0) Some(x / 2) else None
def main(args: Array[String]): Unit = {
val n: Option[Int] = Some(8)
val nested = n.map(half)
println(nested)
}
}Using flatMap
flatMap applies a function that returns an Option and flattens the result into a single Option.
Compare this output to the nested version from the previous scene.
object Main {
def half(x: Int): Option[Int] = if (x % 2 == 0) Some(x / 2) else None
def main(args: Array[String]): Unit = {
val n: Option[Int] = Some(8)
val flat = n.flatMap(half)
println(flat)
}
}Chaining flatMap
Because each step returns an Option, you can chain several flatMap calls. If any step yields None, the whole chain becomes None.
object Main {
def half(x: Int): Option[Int] = if (x % 2 == 0) Some(x / 2) else None
def main(args: Array[String]): Unit = {
val result = Some(16).flatMap(half).flatMap(half)
println(result)
}
}Short-Circuiting on None
If a middle step returns None, later steps are skipped and the final result is None.
This automatic short-circuiting removes manual null checks.
object Main {
def half(x: Int): Option[Int] = if (x % 2 == 0) Some(x / 2) else None
def main(args: Array[String]): Unit = {
val result = Some(8).flatMap(half).flatMap(half)
println(result)
}
}Combining map and flatMap
Use flatMap for steps that return an Option and map for the final plain transformation.
object Main {
def parse(s: String): Option[Int] = s.toIntOption
def main(args: Array[String]): Unit = {
val result = Some("21").flatMap(parse).map(_ * 2)
println(result)
}
}Why map and flatMap?
These methods let you:
- Transform values without unwrapping
- Skip work automatically on
None - Chain operations that might fail
- Avoid nested
Option[Option[A]]with flatten
Putting It Together
A realistic chain: look up a key, parse it, then transform, all safely.
object Main {
val config = Map("port" -> "8080")
def main(args: Array[String]): Unit = {
val port = config.get("port").flatMap(_.toIntOption).map(_ + 1)
println(port)
val missing = config.get("host").flatMap(_.toIntOption)
println(missing)
}
}Quick Check
Test your understanding of map and flatMap.
Recap
You learned to compose Options:
maptransforms the value inside aSome, leavingNonealoneflatMapapplies a function returning an Option and flattens the result- Chaining short-circuits to
Noneif any step isNone - Use
flatMapfor Option-returning steps,mapfor plain ones
Preguntas frecuentes
¿La lección «map y flatMap sobre Option» es gratis?
Sí — el texto completo de «map y flatMap sobre Option» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Scala for Backend Engineering & Functional Programming, actualiza a CoddyKit PRO. El curso de Scala for Backend Engineering & Functional Programming incluye 4 lecciones en total.
¿Qué aprenderé en «map y flatMap sobre Option»?
Componga de forma segura Practicas Scala for Backend Engineering & Functional Programming con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Scala for Backend Engineering & Functional Programming?
No se requiere experiencia previa. Scala for Backend Engineering & Functional Programming en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.
¿Cuánto tiempo toma la lección «map y flatMap sobre Option»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Scala for Backend Engineering & Functional Programming?
Sí. Cada lección de Scala for Backend Engineering & Functional Programming incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Cómo evitar null
- map y flatMap sobre Option
- getOrElse y fold
- Option en for-comprehensions