An introduction to Scala macros

Akash Srivastava
Walmart Global Tech Blog
3 min readMay 7, 2020

--

source: google-images

Hey guys, it’s been a while since my last post. So continuing with our journey in functional programming, today I have planned to cover a slightly advanced concept of “compile-time code manipulation” in Scala. For the introduction, I would keep it simple as it involves some working knowledge of the Scala compiler.

What are Scala macros?

To put it simply, macros are an experimental feature in Scala, that allows us to do stuff during compile-time.

What kind of stuff?

Well, for starters we can modify existing code or even generate new code during the macro expansion, after which it gets compiled.

Hmm, ok, where is it used?

Scala macros are internally used by many known libraries in the Scala ecosystem. Some of them are Shapeless, Play, Slick, etc.

And.. how does it work?

Here comes the compiler knowledge I was blabbering about :P. Scala macros expose the API for playing with the AST (Abstract Syntax Tree) used by the compiler. Each line of code we write goes through 25 phases of compilation in the Scala compiler. In the Parser phase, the code is transformed into this AST, which goes through the other phases of the compiler: type-checking, inlining, un-currying, lambda expansion, and finally bytecode generation.

--

--