Implicit Parameters
Context passing.
Passing context automatically
Implicit parameters let the compiler supply an argument for you, drawn from values marked implicit in scope. They are great for passing 'ambient' context like configuration or formatting rules.
object Main {
def greet(name: String)(implicit greeting: String): String =
s"$greeting, $name!"
implicit val defaultGreeting: String = "Hello"
def main(args: Array[String]): Unit = {
println(greet("Ann"))
}
}The implicit parameter list
Mark the last parameter list with the implicit keyword. When you omit it at the call site, the compiler searches for a matching implicit value.
object Main {
def multiply(x: Int)(implicit factor: Int): Int = x * factor
implicit val f: Int = 10
def main(args: Array[String]): Unit = {
println(multiply(5))
}
}All lessons in this course
- Implicit Parameters
- Scala 3 given/using
- Implicit Conversions
- Extension Methods