Reading — step 1 of 5
Learn
~1 min readImplicits and Type Classes
Scala 2's implicits let the compiler fill in arguments from context. They power type classes, dependency injection, and more.
implicit val multiplier: Int = 3
def scale(n: Int)(implicit m: Int): Int = n * m
scale(5) // 15 — multiplier filled in automatically
scale(5)(10) // 50 — explicit override
Common use case — passing context like an ExecutionContext:
import scala.concurrent._
implicit val ec: ExecutionContext = ExecutionContext.global
Future { computeStuff() } // ec is filled in implicitly
Implicit conversions turn one type into another. Scala 2's most contentious feature — useful but easy to misuse:
import scala.language.implicitConversions
implicit def intToString(n: Int): String = n.toString
val s: String = 42 // works because the conversion is in scope
Implicit classes add methods to existing types ("extension methods"):
implicit class IntOps(val n: Int) extends AnyVal {
def square: Int = n * n
def isEven: Boolean = n % 2 == 0
}
5.square // 25
6.isEven // true
The compiler wraps 5 in an IntOps, calls square, returns the result. With extends AnyVal the wrapper is optimized away — no allocation.
Note: Scala 3 replaces this with given/using/extension keywords. The mechanics are the same; the syntax is cleaner.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…