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

Currying क्या है

Currying कई inputs वाले function को एक chain of steps में तोड़ देता है जिनमें हर एक सिर्फ एक input लेता है, जैसे पहले pizza का size order करना फिर toppings। आप inputs को चरणों में दे सकते हैं।

In this page:

  1. Currying
Syntax
scala
def function_name(a: Type)(b: Type): ReturnType = expression

function_name(value1)(value2)

Currying

एक curried function कई parameter lists के साथ declare किया जाता है, जैसे def add(a: Int)(b: Int): Int, जो आपको इसे सभी arguments एक साथ call करने या उन्हें एक समय में एक list apply करने देता है।

सिर्फ पहले parameter list से इसे call करने पर बाकी की उम्मीद करने वाला एक नया function मिलता है। Currying reusable, आंशिक रूप से configured functions बनाने के लिए उपयोगी है और Scala के trailing function argument को block के रूप में पास करने वाले syntax के साथ खासतौर पर अच्छा काम करता है।

Note: Curried functions ही Scala के block-syntax method calls को संभव बनाते हैं, जैसे list.foldLeft(0) { (acc, x) => acc + x }।

उदाहरण: Currying

markup
object Main extends App {
  def add(a: Int)(b: Int): Int = a + b

  println(add(3)(4))

  val addFive = add(5) _
  println(addFive(10))
}
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. किसी curried method पर add(3, 4) call करना, जो error देता है क्योंकि इसमें दो parameter lists हैं।
  2. Scala 2 में _ के बिना add(5) लिखना और missing argument list error पाना।
  3. currying को default parameters के साथ confuse करना, जबकि currying किसी function को steps में बांटता है।
🔒

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.