Discuss the role and mechanisms of macros in Scala for metaprogramming.
Instruction: Explain how macros work in Scala and how they can be used for metaprogramming, providing examples.
Updated
A Scala 3 macro is an inline entry point whose splice calls a compile-time implementation. The implementation receives typed expressions and produces a typed expression to insert into the caller. The generated program runs later, at runtime.
For example, generate a computation that evaluates its argument once and doubles the resulting BigInt. Define the macro in Twice.scala:
import scala.quoted.*
object Twice {
inline def apply(inline value: BigInt): BigInt = ${ twiceImpl('value) }
private def twiceImpl(value: Expr[BigInt])(using Quotes): Expr[BigInt] =
'{ val once = $value; once + once }
}
Use it from a different source file, UseTwice.scala:
@main def macroExample(): Unit = {
var calls = 0
val result = Twice { calls += 1; BigInt(21) }
assert(result == 42 && calls == 1)
}
Compile both files with Scala 3, or compile the macro definition first and make it available on the user's classpath. The macro implementation cannot be called from the same source file where it is defined. The quoted local once preserves single evaluation: splicing the original argument into both addition operands would repeat its side effects. BigInt avoids fixed-width overflow, while its arithmetic still has allocation and size-dependent costs. Quotes, splices and macros
An ordinary method could implement this particular operation more simply; the example exposes staging and evaluation semantics. More substantial macros can derive encoders, inspect expression structure or reject invalid static inputs. They cannot generally prove facts about an arbitrary runtime collection, such as the absence of nulls, just by running during compilation.
Prefer typed quotes and quoted patterns to low-level reflection where possible. Test positive expansion, invalid input diagnostics, generated behavior and side effects with the supported compiler. Generated code can still be logically wrong, and a macro does not automatically improve performance. Scala 2 blackbox/whitebox macros use a different system and require migration work.