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

for Comprehension के Basics

एक for comprehension एक ऐसा for loop है जो एक साथ कई lists का उपयोग कर सकता है और उन items को छोड़ सकता है जो फिट नहीं बैठते। यह हर shirt को हर pant के साथ match करने जैसा है लेकिन सिर्फ अच्छे outfits रखना।

In this page:

  1. for Comprehension Basics
Syntax
scala
for {
  x <- collection1
  y <- collection2
  if condition
} {
  // body
}

for Comprehension Basics

एक for comprehension में कई generators और filters शामिल हो सकते हैं, जैसे for (x <- 1 to 3; y <- 1 to 3 if x != y) { ... }, जो combinations पर iterate करते हुए inline अवांछित वालों को filter कर देता है।

यह एक basic single-generator loop से ज़्यादा powerful है और declarative रूप से पढ़ी जाती है। yield (जिसका अपना tutorial है) के साथ मिलकर, for comprehensions सिर्फ side effects चलाने के बजाय नई collections बनाने का एक तरीका बन जाते हैं।

Note: किसी for comprehension के generators के अंदर एक if, body में अलग if statement की ज़रूरत के बिना elements को inline filter करता है।

उदाहरण: for Comprehension Basics

markup
object Main extends App {
  for (x <- 1 to 3; y <- 1 to 3 if x != y) {
    println(s"($x, $y)")
  }
}
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. if से एक filter जोड़ना और यह भूल जाना कि यह उससे पहले वाले generator पर लागू होता है, जिससे pairs अनपेक्षित रूप से छूट जाते हैं।
  2. generators के बीच comma या गलत separator का उपयोग करना, जबकि उन्हें ; या नई lines से अलग किया जाता है।
  3. nested output order को पहले y की उम्मीद करना, जबकि आखिरी generator (y) सबसे तेज़ बदलता है।
🔒

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.