नेस्टेड Functions
एक nested function एक बड़े function के अंदर defined एक छोटा helper है, जैसे किसी toolbox के अंदर रखा एक औज़ार। सिर्फ बड़ा function इसे देख और उपयोग कर सकता है।
In this page:
Syntax
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
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)))
}
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. #}
आम गलतियां
- inner function को enclosing function के बाहर से call करना, जो fail हो जाता है क्योंकि वह वहां दिखाई नहीं देता।
- nested function को उस code के बाद define करना जो उसे इस तरह उपयोग करता है कि एक uninitialised value reference हो जाए।
- एक ही helper को ऊंचे स्तर पर एक बार define करने के बजाय कई functions में कॉपी करना।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: