Currying क्या है
Currying कई inputs वाले function को एक chain of steps में तोड़ देता है जिनमें हर एक सिर्फ एक input लेता है, जैसे पहले pizza का size order करना फिर toppings। आप inputs को चरणों में दे सकते हैं।
In this page:
Syntax
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
object Main extends App {
def add(a: Int)(b: Int): Int = a + b
println(add(3)(4))
val addFive = add(5) _
println(addFive(10))
}
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. #}
आम गलतियां
- किसी curried method पर
add(3, 4)call करना, जो error देता है क्योंकि इसमें दो parameter lists हैं। - Scala 2 में
_के बिनाadd(5)लिखना औरmissing argument listerror पाना। - currying को default parameters के साथ confuse करना, जबकि currying किसी function को steps में बांटता है।
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: