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

Closures क्या हैं

एक closure एक function है जो बनते समय अपने आस-पास के variables को याद रखता है, जैसे एक lunchbox जिसमें वही होता है जो आपने पैक किया था। बाद में भी, यह उन values का उपयोग कर सकता है।

In this page:

  1. Closures
Syntax
scala
var captured = value
val closure = (param: Type) => param + captured    // uses captured from the outer scope

Closures

एक closure एक ऐसा function है जो अपने enclosing scope से variables को capture करता है, और उस scope के technically चलना खत्म करने के बाद भी उन्हें reference करता रहता है।

यह आपको ऐसे functions बनाने देता है जो अपनी private, याद रखी गई state रखते हैं। Closures ही counters या configurable multiplier functions जैसे patterns को बिना किसी class के संभव बनाते हैं।

Note: एक closure variable को खुद capture करता है, सिर्फ बनते समय की उसकी value नहीं -- अगर captured var बाद में बदल जाए, तो closure नई value देखता है।

उदाहरण: Closures

markup
object Main extends App {
  def makeMultiplier(factor: Int): Int => Int = {
    (x: Int) => x * factor
  }

  val triple = makeMultiplier(3)
  val double = makeMultiplier(2)

  println(triple(5))
  println(double(5))
}
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. यह उम्मीद करना कि कोई closure factor की value को copy कर लेगा, जबकि यह variable को capture करता है, इसलिए बाद में बदलने वाला var इसे प्रभावित करता है।
  2. किसी var पर loop में closures बनाना और हैरान होना कि वे एक ही variable share करते हैं।
  3. makeMultiplier पर return type Int => Int भूल जाना, जिससे compiler result को स्पष्ट रूप से infer नहीं कर पाता।
🔒

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.