Option の map と flatMap
安全に処理を合成します。
「Option の map と flatMap」はCoddyKit上の無料Scala for Backend Engineering & Functional Programmingレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはScala for Backend Engineering & Functional Programming学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Scala for Backend Engineering & Functional Programmingコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
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
よくある質問
「Option の map と flatMap」レッスンは無料ですか?
はい。「Option の map と flatMap」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Scala for Backend Engineering & Functional Programmingコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Scala for Backend Engineering & Functional Programmingコースには全4レッスンが含まれています。
「Option の map と flatMap」で何を学びますか?
安全に処理を合成します。 ブラウザで直接実行するハンズオンコードでScala for Backend Engineering & Functional Programmingを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Scala for Backend Engineering & Functional Programmingを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのScala for Backend Engineering & Functional Programmingは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。
「Option の map と flatMap」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このScala for Backend Engineering & Functional Programmingレッスンでコードを書いて実行できますか?
はい。すべてのScala for Backend Engineering & Functional Programmingレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- null を避ける
- Option の map と flatMap
- getOrElse と fold
- for 内の Option