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

Anonymous Functions क्या हैं

एक anonymous function एक छोटा नामहीन helper है जो तुरंत लिखा जाता है, जैसे instructions का एक quick note। यह हर number को double करने जैसे छोटे कामों के लिए सुविधाजनक है।

In this page:

  1. Anonymous Functions
Syntax
scala
val function_name = (param: Type) => expression
val other = (a: Type, b: Type) => expression
collection.map(_ * 2)

Anonymous Functions

एक anonymous function (या "lambda") एक function value है जिसे बिना नाम के inline लिखा जाता है, (params) => expression syntax का उपयोग करके, जिसे आमतौर पर सीधे map जैसे higher-order function को पास किया जाता है।

Underscore placeholder _ simple single-argument cases के लिए एक और भी compact shorthand देता है, जैसे _ * 2। Anonymous functions छोटे, एक-बार के logic के लिए पूरी named def के formalities से बचाते हैं।

Note: Underscore shorthand, जैसे numbers.map(_ * 2), एक simple single-parameter anonymous function लिखने का Scala का सबसे संक्षिप्त तरीका है।

उदाहरण: Anonymous Functions

markup
object Main extends App {
  val numbers = List(1, 2, 3, 4)

  val squared = numbers.map(n => n * n)
  val doubled = numbers.map(_ * 2)

  println(squared)
  println(doubled)
}
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. numbers.map(_ * _) जैसे _ को दो बार उपयोग करना और एक value की उम्मीद करना, जबकि हर underscore एक अलग parameter को represent करता है।
  2. map(foo(_ + 1)) जैसे किसी nested expression के अंदर _ का उपयोग करना, जहां यह गलत function में expand हो जाता है।
  3. n => n * n के बजाय n -> n * n लिखना, जबकि -> एक tuple बनाता है।
🔒

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.