What are 'Macros' in Scala and how are they used?

Instruction: Discuss Scala Macros, their purposes, and examples of their use.

Context: This question assesses the candidate's knowledge of Scala Macros, a powerful feature for metaprogramming that allows programmers to write code that generates code at compile time, enhancing the expressiveness and capabilities of Scala programs.

Updated

Macros analyze or generate code during compilation. In Scala 3, an inline entry point invokes a macro implementation that works with typed expressions and a Quotes context. Quotes represent code; splices insert generated expressions into it. Scala 2 macro APIs are different. Scala 3 macros

For example, this macro produces a diagnostic label and its integer result. Put the definition in Inspect.scala:

import scala.quoted.*
object Inspect {
  inline def showValue(inline value: Int): String =
    ${ showValueImpl('value) }

  private def showValueImpl(value: Expr[Int])(using Quotes): Expr[String] = {
    val label = Expr(value.show)
    '{ val evaluated = $value; $label + " = " + evaluated }
  }
}

Use it from a separate Main.scala file, compiling the macro implementation before expanding its call:

@main def macroExample(): Unit = {
  var evaluations = 0
  val result = Inspect.showValue({ evaluations += 1; 7 })
  assert(evaluations == 1)
  assert(result.endsWith(" = 7"))
}

The expression's displayed source is captured at compilation; its value is computed at runtime. The generated local binding evaluates the argument once, preserving that behavior for side effects. Exact source formatting is compiler-dependent, so the assertion checks the result suffix rather than a particular printed expression. Quotes and splices

Useful applications include deriving repetitive serializers or type-class instances and checking a DSL whose relevant input is available at compilation. Prefer ordinary methods, inline operations or existing derivation tools when they suffice. A macro adds compiler-version, diagnostic and maintenance costs; generated code still needs tests. Static type checking does not prove business correctness, eliminate runtime failures or establish a performance improvement. Test invalid input diagnostics and generated runtime behavior, and measure compilation and execution separately.

Related Questions