Explicit defaults in Scala

This post is another entry in my series on stuff you should never do with macros in Scala, but that you could do with macros in Scala, if you really wanted to, and if you’d picked up a bottle of Macallan on the way home from work and were willing to waste half an evening doing something ridiculously useless.

It’s specifically a response to this Stack Overflow question, which asks if it’s possible to specify explicitly that you want to use the default value of a constructor parameter in Scala.

So suppose we have a class like this:

The goal is to allow the following syntax:

This is possible with macros, and it’s not nearly as easy as you might think.

Here’s the code:

This is so horrible I’m not going to waste time commenting on it at all. But it works:

It’ll currently choke (fairly gracefully) on auxiliary constructors and constructors with multiple parameter lists, and it won’t work at all on any methods except constructors. All these limitations could be addressed pretty easily, but I’ll leave that to someone who actually wants to use this awful syntax.