4

It is trivial to write a macro to convert bytes"hello" into

"hello".getBytes or Array('h'.getByte, 'o'.getByte, 'l'.getByte, 'l'.getByte, 'o'.getByte)

The problem here is we do not get the constant literal, i.e "hello" eq "hello" does not hold for the values constructed by the macros: bytes"hello" ne bytes"hello". There is also a performance drawback as the byte array is needlessly constructed many times.

What actually bytes"hello" has to be converted is a global scope object:

object `bytes"hello"` {
  val value = Array('h'.getByte, 'o'.getByte, 'l'.getByte, 'l'.getByte, 'o'.getByte)
}

But it seems that in its current state, Scala Macros does not allow creation of global objects. Am I wrong and this is doable in the current Scala ?

  • How important is it to you that the computation happen at compile time? If it's not important, you could defer to a runtime caching system. – Brian McCutchon Jul 05 '19 at 23:43
  • It is important to create an object in a higher scope than the macro expansion. Creating constants is just an example, not the problem to solve or to workaround. There are many other application for the top-level objects made by macros: global caches, etc – Nathan Rabinovich Jul 06 '19 at 02:02
  • Caching can be done at runtime. The point of macros is to do local code transformations, as I understand it, so I suspect that such global modifications are not possible. – Brian McCutchon Jul 07 '19 at 23:11
  • I guess the trick could be done by macros + annotation processor, which could produce a new file – Nathan Rabinovich Aug 05 '19 at 10:54

0 Answers0