for Comprehension के Basics
एक for comprehension एक ऐसा for loop है जो एक साथ कई lists का उपयोग कर सकता है और उन items को छोड़ सकता है जो फिट नहीं बैठते। यह हर shirt को हर pant के साथ match करने जैसा है लेकिन सिर्फ अच्छे outfits रखना।
In this page:
Syntax
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
object Main extends App {
for (x <- 1 to 3; y <- 1 to 3 if x != y) {
println(s"($x, $y)")
}
}
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
ifसे एक filter जोड़ना और यह भूल जाना कि यह उससे पहले वाले generator पर लागू होता है, जिससे pairs अनपेक्षित रूप से छूट जाते हैं।- generators के बीच comma या गलत separator का उपयोग करना, जबकि उन्हें
;या नई lines से अलग किया जाता है। - nested output order को पहले
yकी उम्मीद करना, जबकि आखिरी generator (y) सबसे तेज़ बदलता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: