Fundamentos de macros
Código em tempo de compilação.
Fundamentos de macros é uma aula grátis de Scala for Backend Engineering & Functional Programming no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Scala for Backend Engineering & Functional Programming, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Scala for Backend Engineering & Functional Programming inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
What Is a Macro?
A macro is code that runs at compile time to generate other code. Scala 3 macros let you inspect arguments, build expressions, and emit them into the program before it is compiled.
Inline + Macro Pattern
A macro is invoked from an inline def that delegates to a method marked with ${ ... }. The inline def is the public API; the macro impl runs in the compiler.
import scala.quoted.*
inline def power(x: Double, inline n: Int): Double =
${ powerImpl('x, 'n) }The Quotes Context
Every macro implementation takes an implicit Quotes context. It grants access to the reflection API and the ability to build and splice expressions.
import scala.quoted.*
def powerImpl(x: Expr[Double], n: Expr[Int])(using Quotes): Expr[Double] =
???Expr[T]
Expr[T] represents a typed expression of type T as compile-time data. Macros receive and return Expr values.
Lifting Values to Expr
Expr(value) lifts a runtime value computed in the macro into an expression to splice back. This works for any type with a ToExpr instance.
import scala.quoted.*
def constImpl(using Quotes): Expr[Int] = Expr(42)Extracting Constant Arguments
n.value (or n.valueOrAbort) extracts the constant behind an Expr when the argument is statically known, so the macro can branch on it.
import scala.quoted.*
def powerImpl(x: Expr[Double], n: Expr[Int])(using Quotes): Expr[Double] = {
val exp = n.valueOrAbort
??? // build x*x*...*x exp times
}Reporting Errors
Use quotes.reflect.report.errorAndAbort to emit a compile error with a message and location when the macro's preconditions are not met.
import scala.quoted.*
def check(n: Expr[Int])(using q: Quotes): Expr[Int] = {
import q.reflect.*
val v = n.valueOrAbort
if (v < 0) report.errorAndAbort("must be >= 0")
Expr(v)
}Where Macros Live
Macro implementations must be compiled before the code that uses them — typically in a separate file or module. The compiler executes them while compiling the caller.
Common Use Cases
Macros power:
- typeclass derivation (JSON codecs, etc.)
- compile-time validation (regex, SQL)
- logging that captures source positions
- zero-cost abstractions
Safety and Hygiene
Scala 3 macros are hygienic: generated identifiers cannot accidentally capture user variables, and the type system checks generated code, preventing many classic macro bugs.
Runtime Equivalent
A macro that computes a power at compile time produces the same result as this self-contained runtime version — but with the multiplications baked in by the compiler.
object Main {
def power(x: Double, n: Int): Double =
if (n == 0) 1.0 else x * power(x, n - 1)
def main(args: Array[String]): Unit = {
println(power(2.0, 3)) // 8.0
}
}Quick Check
What type represents a typed compile-time expression that macros receive and return?
Recap
You learned macro basics:
- macros run at compile time via the
inline def ... ${ }pattern Quotescontext andExpr[T]- lifting with
Expr(...)and extracting with.value - error reporting and hygiene
Next: quotes and splices.
Perguntas Frequentes
A aula “Fundamentos de macros” é grátis?
Sim — o texto completo de “Fundamentos de macros” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Scala for Backend Engineering & Functional Programming, atualize para CoddyKit PRO. O curso de Scala for Backend Engineering & Functional Programming inclui 4 aulas no total.
O que vou aprender em “Fundamentos de macros”?
Código em tempo de compilação. Você pratica Scala for Backend Engineering & Functional Programming com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Scala for Backend Engineering & Functional Programming?
Nenhuma experiência prévia é necessária. Scala for Backend Engineering & Functional Programming no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.
Quanto tempo leva a aula “Fundamentos de macros”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Scala for Backend Engineering & Functional Programming?
Sim. Cada aula de Scala for Backend Engineering & Functional Programming inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Métodos inline
- Fundamentos de macros
- Quotes e splices
- Macros práticas