During the running of a scala script, I would like it to generate some code and execute this.
I thought I had found two examples online that might work, but they aren't successful
import scala.reflect.runtime.universe._
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox
import java.io.{File, FileWriter}
def runstuff() = {
val fileWriter = new FileWriter(new File("temporaryScalaFile.scala"))
fileWriter.write("println(\"hello\")")
fileWriter.close()
temporaryScalaFile.scala
val cm = scala.reflect.runtime.universe.runtimeMirror(getClass.getClassLoader)
val tb = cm.mkToolBox()
val str = tb.eval(tb.parse("new String(\"Yo\")"))
println(str)
}
These are perhaps out of date examples.
Does anyone have a working one or a fix?
I'll adopt to Scala 2 my answer in How to compile and execute scala code at run-time in Scala3?
build.sbt
build.sbt
or
build.sbt
scala.tools.nsc.interpreterbuild.sbt
scala.reflect.runtime.universe.Treeq"..."rather than plain string then you don't need to parsebuild.sbt
scala.reflect.runtime.universe.Exprreify {...}(a statically typed wrapper over a tree) rather than plain string then you also don't need to parsebuild.sbt
build.sbt
scala-compilerorscala3-compilerin your classpath you will run Scala 2 or Scala 3 (one of the two above script engines: Scala 2scala.tools.nsc.interpreter.shell.Scriptedor Scala 3dotty.tools.repl.ScriptEngine). If you have both the dependency added first wins.If you'd like to have a better control what dependency is used (without re-importing the project) you can use Coursier and specify class loader
build.sbt
scala.meta.interactive.InteractiveSemanticdb.newCompiler()returning ascala.tools.nsc.interactive.Globalextending abovescala.tools.nsc.Global.build.sbt
Scala reflection: compile akka actor with protobuf
Dynamic compilation of multiple Scala classes at runtime
How to eval code that uses InterfaceStability annotation (that fails with "illegal cyclic reference involving class InterfaceStability")?
Tensorflow in Scala reflection
Scala Presentation Compiler - Minimal Example
What is "Scala Presentation Compiler"?
"eval" in Scala