Quotes and Splices
Quotes and splices are tools that let a program treat code as data. A quote stores code, and a splice runs code during compilation.
A macro definition and an inline doubling both give 6
The macro method is defined with a quote and a splice. The inline method doubles 3 and prints 6.
import scala.quoted.*
def doubleIt(expr: Expr[Int])(using Quotes): Expr[Int] = '{ $expr + $expr }
inline def twice(x: Int): Int = x + x
@main def main(): Unit =
println(twice(3))A macro definition and a compile-time value both give 7
The macro method is defined with a quote and a splice. The compile-time operation reads 7 from its type.
import scala.quoted.*
import scala.compiletime.constValue
def addOne(expr: Expr[Int])(using Quotes): Expr[Int] = '{ $expr + 1 }
@main def main(): Unit =
println(constValue[7])A macro definition and an uppercase word both give HI
The macro method is defined with a quote and a splice. The main program prints the uppercase form of hi.
import scala.quoted.*
def shout(expr: Expr[String])(using Quotes): Expr[String] = '{ $expr.toUpperCase }
@main def main(): Unit =
println("hi".toUpperCase)Example
import scala.quoted.*
import scala.compiletime.{constValue, summonInline}
def doubleIt(expr: Expr[Int])(using Quotes): Expr[Int] = '{ $expr + $expr }
def addOne(expr: Expr[Int])(using Quotes): Expr[Int] = '{ $expr + 1 }
given Int = 8
inline def twice(x: Int): Int = x + x
@main def main(): Unit =
println(twice(3))
println(constValue[7])
println(summonInline[Int])Key points
- Quote: A quote is code wrapped so it can be handled as data.
- Splice: A splice is a marker inside a quote that inserts the result of another expression.
- Macro: A macro is a method that builds code during compilation.
- Quotes context: A Quotes context is the setting a macro method needs before it can use a quote.
- Use a quote inside a macro method to build a new expression.
- Rule: A quote needs a Quotes context, so a plain main program cannot run a quote on its own.
In this example, two macro methods are defined with quotes and splices. The given value for Int is 8 and the inline method doubles its input. The main program then prints the inline doubling, the compile-time value, and the given value.
Note
Scala requires a macro to be compiled before it is used, so a macro cannot be called in the same source file where it is defined.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
Why can a macro not be called in the same file where it is defined?