map وflatMap على Option
التركيب بأمان
map وflatMap على Option درس مجاني في Scala for Backend Engineering & Functional Programming على CoddyKit. هذا هو الدرس 2 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في 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
الأسئلة الشائعة
هل درس «map وflatMap على Option» مجاني؟
نعم — نص درس «map وflatMap على Option» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Scala for Backend Engineering & Functional Programming، انتقل إلى CoddyKit PRO. تتضمن دورة Scala for Backend Engineering & Functional Programming 4 دروس في المجموع.
ماذا ستتعلم في «map وflatMap على Option»؟
التركيب بأمان تتمرن على Scala for Backend Engineering & Functional Programming مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ Scala for Backend Engineering & Functional Programming؟
لا تُشترط خبرة سابقة. Scala for Backend Engineering & Functional Programming على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 2 من أصل 4.
كم من الوقت يستغرق درس «map وflatMap على Option»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس Scala for Backend Engineering & Functional Programming هذا؟
نعم. كل درس في Scala for Backend Engineering & Functional Programming يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- تجنب null
- map وflatMap على Option
- getOrElse وfold
- Option في for-comprehensions