What are macros used for in Scala? What can be done with a Macro that cannot be done with a function?
I suppose one advantage are:
- The ability to parse the AST at the call point, but that's a fairly rare use case.
- The code doesn't result in an extra function call (modifying the AST directly instead), but modern compilers are pretty good at inlining functions.
Are there any other advantages I'm missing?
The advantage of macros is seen most when it prevents you from writing code in the first place.
Consider the case of play-json. I can define a case class, and the play-json formatter macros can create methods which convert my CC to and from json using the fields I've defined on the class.
The key thing here is that it's taking part of the source code which is not usually represented at runtime (the names of the variables) and it does compile-time (type-safe!) reflection on them to create specific functions instead of using runtime (unsafe) reflection.