← Back to Scala Course | Chapter 12: Advanced Features | Lesson 1 of 7

Implicit Parameters क्या हैं

एक implicit parameter एक ऐसा input है जिसे Scala अपने आप भर देता है, जैसे एक waiter जो बिना पूछे आपका usual order ले आता है। आपको बस ऐसी एक value को दृष्टि में रखना है।

In this page:

  1. Implicit Parameters
Syntax
scala
def function_name(param: Type)(implicit name: Type): ReturnType = expression

implicit val name: Type = value
function_name(arg)

Implicit Parameters

एक implicit parameter compiler को किसी scope में मौजूद implicit val/def से अपने आप एक argument प्रदान करने देता है, अगर caller explicitly एक नहीं देता।

यह आमतौर पर contextual configuration पास करने के लिए उपयोग होता है, जैसे कोई formatting rule या execution context, बिना इसे हर call में explicitly पिरोए। किसी समय में किसी दिए गए type की सिर्फ एक implicit value scope में हो सकती है बिना ambiguity errors के।

Note: अगर compiler 'could not find implicit value' report करे, तो इसका मतलब है कि उस parameter के type के लिए scope में कोई matching implicit definition नहीं है।

उदाहरण: Implicit Parameters

markup
object Main extends App {
  implicit val defaultGreeting: String = "Hello"

  def greet(name: String)(implicit greeting: String): Unit = {
    println(s"$greeting, $name!")
  }

  greet("Alice") // uses the implicit defaultGreeting
  greet("Bob")("Hi") // explicitly overridden
}
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. scope में एक ही type की दो implicit values define करना, जिससे ambiguous implicit values error आता है।
  2. यह भूल जाना कि implicit parameter list आखिरी होनी चाहिए, जैसे def greet(name: String)(implicit greeting: String)।
  3. हर चीज़ के लिए implicit का उपयोग करना, जिससे यह देखना मुश्किल हो जाता है कि values कहां से आती हैं; Scala 3 given और using उपयोग करता है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 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.