Implicit Parameters
An implicit parameter is an input Scala fills in for you automatically, like a waiter who brings your usual order without you asking. You just need one such value to be in view.
In this page:
Syntax
def function_name(param: Type)(implicit name: Type): ReturnType = expression
implicit val name: Type = value
function_name(arg)
Implicit Parameters
An implicit parameter lets the compiler automatically supply an argument from an in-scope implicit val/def, if the caller doesn't provide one explicitly.
This is commonly used for passing along contextual configuration, like a formatting rule or execution context, without threading it explicitly through every call. Only one implicit value of a given type can be in scope at a time without ambiguity errors.
Note:
If the compiler reports 'could not find implicit value', it means no matching implicit definition is in scope for that parameter's type.
Example: 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. #}
Common Mistakes
- Defining two
implicitvalues of the same type in scope, causing anambiguous implicit valueserror. - Forgetting that the implicit parameter list must be last, as in
def greet(name: String)(implicit greeting: String). - Using
implicitfor everything, which makes it hard to see where values come from; Scala 3 usesgivenandusing.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: