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.
Previous
What is the cake pattern in Scala?
Next
What is ZIO and how does it compare to Cats Effect?
More Scala Questions
View all →- Intermediate What is the type class pattern in Scala?
- Intermediate What is Akka and what is the actor model?
- Intermediate What is Apache Spark and how does Scala relate to it?
- Intermediate What is Scala's approach to concurrency with Futures and Promises?
- Intermediate What are Scala's monads and how do they work?