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

Higher-Order Functions क्या हैं

एक higher-order function या तो किसी दूसरे function को input के रूप में लेता है या एक वापस देता है, जैसे कोई coach जो चलाने के लिए एक play देता है। यह आपको actions को साधारण values की तरह treat करने देता है।

In this page:

  1. Higher-Order Functions
Syntax
scala
def function_name(f: InputType => OutputType, value: InputType): OutputType = f(value)

def returns_function(): InputType => OutputType = (x: InputType) => expression

Higher-Order Functions

एक higher-order function या तो किसी दूसरे function को parameter के रूप में लेता है, एक function return करता है, या दोनों -- Scala में functions first-class values हैं, जिन्हें किसी भी दूसरी value की तरह store और pass किया जा सकता है।

यह Scala की functional programming style की नींव है, जो आपको सिर्फ data नहीं बल्कि behavior को भी parameterize करने देती है। map और filter जैसे कई standard collection methods higher-order functions हैं।

Note: function type Int => Int एक ऐसे function को describe करता है जो एक Int लेता है और एक Int return करता है, जिसे parameter type के रूप में उपयोग किया जा सकता है।

उदाहरण: Higher-Order Functions

markup
object Main extends App {
  def applyTwice(f: Int => Int, x: Int): Int = {
    f(f(x))
  }

  def addOne(n: Int): Int = n + 1

  println(applyTwice(addOne, 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. method खुद की जगह method का result पास करना, जैसे applyTwice(addOne(1), 5), जबकि एक function की उम्मीद की जाती है।
  2. type गलत करना, जैसे f: Int => Int जबकि एक ऐसा function पास करना जो दो arguments लेता है।
  3. function parameter के return type को भूल जाना, जिससे higher-order function पढ़ना मुश्किल हो जाता है।
🔒

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.