Paramètres implicites
Transmission du contexte
Paramètres implicites est une leçon Scala for Backend Engineering & Functional Programming gratuite sur CoddyKit. Ceci est la leçon 1 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Scala for Backend Engineering & Functional Programming, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Scala for Backend Engineering & Functional Programming comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
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
Questions Fréquemment Posées
La leçon « Paramètres implicites » est-elle gratuite ?
Oui — le texte complet de « Paramètres implicites » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Scala for Backend Engineering & Functional Programming, passe à CoddyKit PRO. Le cours Scala for Backend Engineering & Functional Programming comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Paramètres implicites » ?
Transmission du contexte Tu pratiques Scala for Backend Engineering & Functional Programming avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Scala for Backend Engineering & Functional Programming ?
Aucune expérience préalable n'est requise. Scala for Backend Engineering & Functional Programming sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 1 sur 4.
Combien de temps prend la leçon « Paramètres implicites » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Scala for Backend Engineering & Functional Programming ?
Oui. Chaque leçon Scala for Backend Engineering & Functional Programming inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Paramètres implicites
- given/using de Scala 3
- Conversions implicites
- Méthodes d’extension