Why it matters

Implicits are what enable libraries like Cats and ZIO. They're also the source of most confusing Scala error messages. Understanding them is essential for reading advanced Scala code, and constraint is essential for writing readable code.

Advertisement

The architecture

Implicit parameters: a method can declare 'implicit ec: ExecutionContext' and the compiler will inject the value at call sites without the caller writing it. Used ubiquitously for Futures, transactions, and configurations.

Implicit conversions: an 'implicit def' from A to B lets A values be used where B is expected. Common but dangerous — hides conversions.

Three implicit patternsImplicit paramsauto-passedImplicit conversionsauto-castImplicit classesextension methodsType classes use implicit params; extension methods use implicit classes; conversions are usually avoided
Three uses of implicits.
Advertisement

How it works end to end

Type classes: define a trait Show[A] with a method; provide implicit implementations for specific A; use 'implicit s: Show[T]' in generic methods to get type-specific behavior. This is ad-hoc polymorphism without inheritance.

Extension methods via implicit classes: 'implicit class IntOps(i: Int) { def isEven: Boolean = i % 2 == 0 }' adds an isEven method to Int. Called as '5.isEven'.

Scala 3 syntax: 'given ec: ExecutionContext' declares an implicit; 'extension (i: Int) def isEven: Boolean = ...' declares an extension. Much cleaner.