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?

4
  • 3
    You need to add scala-compiler.jar to the classpath. Commented Sep 19, 2011 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? Commented Sep 19, 2011 at 21:42
  • 2
    In addition to tenshi answer, this should help you with examples of Interpreter usage. Commented Sep 19, 2011 at 21:44
  • 1
    @Peter: Yes, that's correct. Grab your version of scala here: scala-lang.org/downloads. Then unzip it and look in the lib folder. I also recommend you to look at sbt. I heard that it's eclipse integration improved lately. Commented Sep 19, 2011 at 21:47

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

8

I recommend you twitter-util's Eval

Comments

2

For scala3 this can be now achieved with dotty:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.