🔴 Scala Intermediate

What are Scala macros and when are they used?

Answer

Scala macros allow programs to be transformed at compile time — they are code that manipulates ASTs (Abstract Syntax Trees) during compilation. In Scala 2, macros were experimental and powerful: import scala.language.experimental.macros; def assert(cond: Boolean): Unit = macro assertImpl. Common uses: Deriving type class instances (e.g., automatically deriving JSON codecs for case classes). Optimizations: inline string interpolations, unrolling loops. Automatic delegation: implementing proxy patterns. Logging: capture source location at call site. Libraries like Circe, Play JSON, Slick, and ScalaTest use macros internally. Scala 3 macros: significantly improved with a cleaner, stable API using Expr[T], Type[T], and Quotes. Inline in Scala 3 handles many use cases without full macros. Macros are a last resort for library authors — use them when type-level abstractions or code generation cannot achieve the desired result.