Scala 3 Macro Tutorial

Scala 3 Macro Tutorial

  • Tutorial
  • Contribute
  • GitHub

›Extra

Tutorial

  • Introduction
  • Inline
  • Scala Compile-time Operations
  • Scala 3 Macros
  • Quoted Code
  • TASTy Reflection

Extra

  • FAQ
  • Best Practices
  • Other Recources
Edit

Best Practices

Inline

Be careful when inlining for performance

To take the most advantage of the JVM JIT optimisations you want to avoid generating large methods.

Macros

Coming soon

Quoted code

Keep quotes readable

  • Try to avoid ${..} with arbitrary expressions inside
    • Use $someExpr
    • Use ${ someExprFrom('localExpr) }

To illustrate, consider the following example:

val x: StringContext = ...
'{ StringContext(${Varargs(stringContext.parts.map(Expr(_)))}: _*) }

Instead we can write the following:

val x: StringContext = ...
val partExprs = stringContext.parts.map(Expr(_))
val partsExpr = Varargs(partExprs)
'{ StringContext($partsExpr: _*) }

The contents of the quote are cleared this way.

Avoid nested contexts

Consider the following code:

val y: Expr[Int] = ...
def body(x: Expr[Int])(using qctx.Nested) =  '{ $x + $y }
'{ (x: Int) => ${ body('x) } }

Instead, use a normal context and pass all needed expressions. This has also the advantage of allowing the function to not be defined locally.

def body(x: Expr[Int], y: Expr[Int])(using QuoteContext) =
  '{ $x + $y }

val y: Expr[Int] = ...
'{ (x: Int) => ${ body('x, y) } }

TASTy reflection

Coming soon

← FAQOther Recources →
  • Inline
    • Be careful when inlining for performance
  • Macros
  • Quoted code
    • Keep quotes readable
    • Avoid nested contexts
  • TASTy reflection
Scala 3 Macro Tutorial
Docs
TutorialContributeFAQ
Community
Chat on GitterDiscuss on Scala Users
More
GitHub
Copyright © 2020 LAMP EPFL