Implicit Parameters
In this page:
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: