← Back to Scala Course | Chapter 5: Functions | Lesson 6 of 7

नेस्टेड Functions

एक nested function एक बड़े function के अंदर defined एक छोटा helper है, जैसे किसी toolbox के अंदर रखा एक औज़ार। सिर्फ बड़ा function इसे देख और उपयोग कर सकता है।

In this page:

  1. Nested Functions
Syntax
scala
def outer(param: Type): ReturnType = {
  def inner(x: Type): ReturnType = {
    // body
  }
  inner(param)
}

Nested Functions

Scala किसी function को दूसरे function के body के अंदर define करने देता है, जिसका scope सिर्फ उस enclosing function तक सीमित है और जो उसके parameters और local variables (एक closure बनाते हुए) तक पहुंच सकता है।

यह छोटे helper logic के लिए उपयोगी है जो सिर्फ एक specific function से संबंधित हो, जिससे outer scope गड़बड़ नहीं होता। Nested functions Scala में functions के first-class, साधारण values होने का एक स्वाभाविक परिणाम हैं।

Note: एक nested function अपने enclosing function के scope से variables को अपने आप capture कर लेता है, उन्हें explicitly पास किए बिना।

उदाहरण: Nested Functions

markup
object Main extends App {
  def processNumbers(numbers: List[Int]): Int = {
    def double(n: Int): Int = n * 2
    numbers.map(double).sum
  }

  println(processNumbers(List(1, 2, 3)))
}
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. inner function को enclosing function के बाहर से call करना, जो fail हो जाता है क्योंकि वह वहां दिखाई नहीं देता।
  2. nested function को उस code के बाद define करना जो उसे इस तरह उपयोग करता है कि एक uninitialised value reference हो जाए।
  3. एक ही helper को ऊंचे स्तर पर एक बार define करने के बजाय कई functions में कॉपी करना।
🔒

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.