Implicit Parameters क्या हैं
एक implicit parameter एक ऐसा input है जिसे Scala अपने आप भर देता है, जैसे एक waiter जो बिना पूछे आपका usual order ले आता है। आपको बस ऐसी एक value को दृष्टि में रखना है।
In this page:
Syntax
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
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
}
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. #}
आम गलतियां
- scope में एक ही type की दो
implicitvalues define करना, जिससेambiguous implicit valueserror आता है। - यह भूल जाना कि implicit parameter list आखिरी होनी चाहिए, जैसे
def greet(name: String)(implicit greeting: String)। - हर चीज़ के लिए
implicitका उपयोग करना, जिससे यह देखना मुश्किल हो जाता है कि values कहां से आती हैं; Scala 3givenऔरusingउपयोग करता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: