22

Is is possible to compile and execute scala code as a string at runtime either in Scala or in Java?

My idea is to build a DSL using Scala then let Java programmers use the DSL inside Java.

I heard that the class scala.tools.nsc.Interpreter can do something like that, but when I imported it inside my scala file, I got "object tools is not a member of package scala."

So could anybody give me a hint?

Jonas
  • 121,568
  • 97
  • 310
  • 388
Peter
  • 509
  • 1
  • 3
  • 10
  • 3
    You need to add **scala-compiler.jar** to the classpath. – tenshi Sep 19 '11 at 21:40
  • Thanks for your quick response. I am coding in an Eclipse environment by the way. So do I need to download scala-compiler.jar then add it to the build path? Where can I find scala-compiler.jar? – Peter Sep 19 '11 at 21:42
  • 2
    In addition to tenshi answer, [this](http://stackoverflow.com/questions/1183645/eval-in-scala/6082750#6082750) should help you with examples of Interpreter usage. – om-nom-nom Sep 19 '11 at 21:44
  • 1
    @Peter: Yes, that's correct. Grab your version of scala here: http://www.scala-lang.org/downloads. Then unzip it and look in the **lib** folder. I also recommend you to look at [sbt](https://github.com/harrah/xsbt). I heard that it's eclipse integration improved lately. – tenshi Sep 19 '11 at 21:47

3 Answers3

17

In 2.10.0 we expose Scala reflection API, which among everything else includes a runtime compilation facility. More details can be found here: Generating a class from string and instantiating it in Scala 2.10.

Community
  • 1
  • 1
Eugene Burmako
  • 13,028
  • 1
  • 46
  • 59
8

I recommend you twitter-util's Eval

gerferra
  • 1,519
  • 1
  • 14
  • 26
2

For scala3 this can be now achieved with dotty:

The sbt dependency is e.g. "org.scala-lang" %% "scala3-compiler" % "3.1.3"