← Back to Scala Course | Chapter 9: Functional Programming | Lesson 8 of 8

flatMap और for-comprehensions

flatMap हर item को एक छोटी list में बदल देता है और फिर उन सभी को एक में flatten कर देता है, जैसे छोटे boxes को एक बड़ी tray में खोलना। यह ऐसे steps chain करने की कुंजी है जो हर एक result produce करते हैं।
Syntax
scala
val result = collection.flatMap(x => other_collection(x))

val same = for {
  x <- collection
  y <- other_collection(x)
} yield y

flatMap and for-comprehensions

flatMap(f) हर element को एक नई collection (या Option) में map करता है और फिर उन सभी results को एक single collection में flatten कर देता है, जिससे वह nested collections बचती हैं जो सिर्फ map छोड़ देता। यह तब ज़रूरी है जब कोई transformation खुद हर input element के लिए शून्य, एक, या कई results produce करता हो।

yield वाला एक for comprehension एक syntactic sugar है जिसे compiler map/flatMap/filter calls की एक chain में translate करता है, यही वजह है कि दोनों approaches समस्याओं की एक ही class को हल करते हैं।

Note: कई <- generators वाला एक for comprehension बिल्कुल nested flatMap/map calls के बराबर है -- compiler इसे इसी तरह desugar करता है।

उदाहरण: flatMap and for-comprehensions

markup
object Main extends App {
  val words = List("hello", "world")

  val letters = words.flatMap(w => w.toList)
  println(letters)

  val pairs = for {
    x <- List(1, 2)
    y <- List("a", "b")
  } yield (x, y)

  println(pairs)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. map का उपयोग करना जब function एक collection return करता है, जिससे flatMap के flat result के बजाय एक nested List[List[Char]] बन जाता है।
  2. flatMap को ऐसा function पास करना जो collection या Option के बजाय एक single value return करे, जो एक type error देता है।
  3. किसी for comprehension में collection types मिलाना, जैसे एक List और एक Option, जिससे एक confusing type error आता है।
चैप्टर सारांश
  • Higher-order functions, map, filter, और reduce सहित, functions लेते या return करते हैं।
  • Anonymous functions, closures, currying, और partial application लचीले functions बनाते हैं।
  • Function composition और for-comprehensions के साथ flatMap operations को combine करते हैं।
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.