隐式参数
传递上下文
隐式参数 是 CoddyKit 上的免费 Scala for Backend Engineering & Functional Programming 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Scala for Backend Engineering & Functional Programming 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Scala for Backend Engineering & Functional Programming 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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))
}
}Providing implicits explicitly
You can always pass an implicit parameter explicitly, overriding the one in scope. This is handy for one-off cases.
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))
println(multiply(5)(2))
}
}Implicit resolution by type
The compiler matches implicits by type, not by name. There must be exactly one matching implicit value in scope, or compilation fails as ambiguous or missing.
object Main {
case class Config(env: String)
def run()(implicit cfg: Config): String = s"running in ${cfg.env}"
implicit val cfg: Config = Config("prod")
def main(args: Array[String]): Unit = {
println(run())
}
}implicitly to summon a value
The implicitly[T] helper fetches the implicit value of type T from scope directly, without naming a parameter.
object Main {
implicit val name: String = "Scala"
def main(args: Array[String]): Unit = {
val n = implicitly[String]
println(n)
}
}Context bound shorthand
A context bound [T: Ordering] is sugar for an implicit parameter of type Ordering[T]. It is common with type classes.
object Main {
def max[T: Ordering](a: T, b: T): T = {
val ord = implicitly[Ordering[T]]
if (ord.gt(a, b)) a else b
}
def main(args: Array[String]): Unit = {
println(max(3, 7))
println(max("apple", "pear"))
}
}Threading context through calls
Implicit parameters shine when many functions need the same context. Mark it implicit once and it flows through nested calls automatically.
object Main {
case class User(name: String)
def log(msg: String)(implicit u: User): Unit =
println(s"[${u.name}] $msg")
def doWork()(implicit u: User): Unit = {
log("started")
log("finished")
}
implicit val current: User = User("admin")
def main(args: Array[String]): Unit = {
doWork()
}
}Where implicits are searched
The compiler looks for implicits in the local scope, in imports, and in the companion objects of the involved types. Companion objects are a tidy place to provide defaults.
object Main {
case class Currency(symbol: String)
object Currency {
implicit val default: Currency = Currency("$")
}
def price(amount: Int)(implicit c: Currency): String = s"${c.symbol}$amount"
def main(args: Array[String]): Unit = {
println(price(50))
}
}Ambiguity errors
If two implicits of the same type are in scope, the compiler reports an ambiguous implicit error. Keep at most one per type, or pass explicitly.
object Main {
def label(x: Int)(implicit unit: String): String = s"$x$unit"
implicit val unit: String = "px"
def main(args: Array[String]): Unit = {
// Only one implicit String in scope -> no ambiguity
println(label(12))
}
}Default-like behavior
Implicit parameters give a form of context-aware defaults: the same function call yields different results depending on which implicit is in scope.
object Main {
def format(n: Double)(implicit decimals: Int): String =
f"$n%.${decimals}f"
implicit val d: Int = 2
def main(args: Array[String]): Unit = {
println(format(3.14159))
println(format(3.14159)(4))
}
}Use implicits sparingly
Implicit parameters are powerful but can make code harder to follow if overused. Reserve them for genuine cross-cutting context like execution contexts, configs, and type-class instances.
object Main {
case class Locale(code: String)
def hello()(implicit loc: Locale): String =
if (loc.code == "tr") "Merhaba" else "Hello"
implicit val loc: Locale = Locale("tr")
def main(args: Array[String]): Unit = {
println(hello())
}
}Quick Check
How does the compiler decide which value to supply for an implicit parameter?
Recap
You learned implicit parameters (Scala 2 style):
- Mark a parameter list
implicitto have it filled automatically - Resolution is by type, must be unique in scope
implicitly[T]summons a value; context bounds[T: TC]are sugar- Search covers local scope, imports, and companion objects
- Use them for cross-cutting context, not everything
常见问题解答
「隐式参数」课时是免费的吗?
是的 — 「隐式参数」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Scala for Backend Engineering & Functional Programming 课程的其余内容,请升级到 CoddyKit PRO。 Scala for Backend Engineering & Functional Programming 课程共包含 4 节课。
「隐式参数」这节课中我会学到什么?
传递上下文 你通过在浏览器中直接运行的动手代码来练习 Scala for Backend Engineering & Functional Programming,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Scala for Backend Engineering & Functional Programming 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Scala for Backend Engineering & Functional Programming 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「隐式参数」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Scala for Backend Engineering & Functional Programming 课中编写并运行代码吗?
能。每节 Scala for Backend Engineering & Functional Programming 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。