map e flatMap em Option
Componha com segurança.
map e flatMap em Option é uma aula grátis de Scala for Backend Engineering & Functional Programming no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Scala for Backend Engineering & Functional Programming, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Scala for Backend Engineering & Functional Programming inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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
Perguntas Frequentes
A aula “map e flatMap em Option” é grátis?
Sim — o texto completo de “map e flatMap em Option” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Scala for Backend Engineering & Functional Programming, atualize para CoddyKit PRO. O curso de Scala for Backend Engineering & Functional Programming inclui 4 aulas no total.
O que vou aprender em “map e flatMap em Option”?
Componha com segurança. Você pratica Scala for Backend Engineering & Functional Programming com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Scala for Backend Engineering & Functional Programming?
Nenhuma experiência prévia é necessária. Scala for Backend Engineering & Functional Programming no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.
Quanto tempo leva a aula “map e flatMap em Option”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Scala for Backend Engineering & Functional Programming?
Sim. Cada aula de Scala for Backend Engineering & Functional Programming inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Evitando null
- map e flatMap em Option
- getOrElse e fold
- Option em for-comprehensions