← Back to Scala Course | Chapter 4: Control Flow | Lesson 7 of 7

for में yield

for loop में yield जोड़ने से यह results को एक नई list में इकट्ठा करता है, जैसे एक मशीन जो हर toy को painted toy में बदलकर उन्हें ढेर कर देती है। सिर्फ दोहराने के बजाय, यह कुछ produce करता है।

In this page:

  1. yield in for
Syntax
scala
val result = for (item <- collection) yield expression
val filtered = for (item <- collection if condition) yield expression

yield in for

किसी for comprehension में yield जोड़ना, for (x <- collection) yield transform(x), हर element को transform करता है और सिर्फ side effects चलाने के बजाय results को source जैसे ही type की एक नई collection में इकट्ठा करता है।

यह functionally .map को call करने के बराबर है (और filters/कई generators के साथ, लगभग .flatMap/.filter के बराबर), लेकिन complex, multi-generator logic के लिए अक्सर ज़्यादा साफ़ पढ़ा जाता है। परिणामी collection का type उस type से मेल खाता है जिस पर iterate किया जा रहा है।

Note: for (x <- xs) yield f(x) एक syntactic sugar है जिसे compiler map/flatMap/filter calls की एक chain में translate करता है।

उदाहरण: yield in for

markup
object Main extends App {
  val numbers = 1 to 5

  val squares = for (n <- numbers) yield n * n
  println(squares)

  val evens = for (n <- numbers if n % 2 == 0) yield n
  println(evens)
}
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. yield के बिना for का उपयोग करना और नई collection की उम्मीद करना, जबकि यह Unit return करता है और सिर्फ body चलाता है।
  2. yield expression में println जैसे side effects डालना, जबकि yield एक value produce करने के लिए है।
  3. किसी Range पर yield का उपयोग करना और result को List के बजाय Vector पाकर हैरान होना, क्योंकि result type source collection का अनुसरण करता है।
चैप्टर सारांश
  • if/else, while, do-while, और for loops program flow को control करते हैं।
  • for comprehensions और yield loops से results बनाते हैं।
  • किसी loop से बाहर निकलने के लिए scala.util.control.Breaks का उपयोग होता है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 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.