1

Currently I'm writing a scala macro library, and I would like to make it usable from java too.

But I cannot think of a way to access scala macro methods form java source code. Is there any way we can use scala macro method from java.

tiran
  • 2,389
  • 1
  • 16
  • 28

2 Answers2

8

Scala macros are instructions for scala compiler, java code is compiled by javac, which has no idea about both scala and scala macros, so I guess the answer is: there is no way to use them from java.

Eugene Burmako
  • 13,028
  • 1
  • 46
  • 59
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
0

This is true that Scala macros are instructions for Scala compiler. So if you want to execute them in Java then in Java you'll have to run Scala compiler

<dependency>
    <groupId>org.scala-lang</groupId>
    <artifactId>scala-reflect</artifactId>
    <version>2.13.10</version>
</dependency>
<dependency>
    <groupId>org.scala-lang</groupId>
    <artifactId>scala-compiler</artifactId>
    <version>2.13.10</version>
</dependency>
// java
import scala.reflect.api.JavaUniverse;
import scala.tools.reflect.ToolBox;

public class App {
  public static void main(String[] args) {
    new App().run();
  }

  public void run() {
    scala.reflect.runtime.package$ runtime = scala.reflect.runtime.package$.MODULE$;
    JavaUniverse universe = runtime.universe();
    JavaUniverse.JavaMirror mirror = universe.runtimeMirror(this.getClass().getClassLoader());
    scala.tools.reflect.package$ toolsReflect = scala.tools.reflect.package$.MODULE$;
    ToolBox<?> toolBox = toolsReflect.ToolBox(mirror).mkToolBox(toolsReflect.mkSilentFrontEnd(), "");
    toolBox.eval(toolBox.parse("Macros.hello()")); // Hello World!
  }
}
// scala
import scala.language.experimental.macros
import scala.reflect.macros.blackbox

object Macros {
  def hello(): Unit = macro hello_impl

  def hello_impl(c: blackbox.Context)(): c.Tree = {
    import c.universe._
    q"""println("Hello World!")"""
  }
}

Is there any trick to use macros in the same file they are defined?

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66