I would like to compile and execute Scala code given as a String at run-time using Scala3. Like for example in Scala 2 I would have used Reflection
import scala.reflect.runtime.universe as ru
import scala.tools.reflect.ToolBox
val scalaCode = q"""println("Hello world!")"""
val evalMirror = ru.runtimeMirror(this.getClass.getClassLoader)
val toolBox = evalMirror.mkToolBox()
toolBox.eval(scalaCode) //Hello world!
If I try to run this code in Scala3 I get
Scala 2 macro cannot be used in Dotty. See https://dotty.epfl.ch/docs/reference/dropped-features/macros.html
To turn this error into a warning, pass -Xignore-scala2-macros to the compiler
How can I translate this code in Scala3?
According to this comment from Professor Odersky it seems the feature your searching for has been intentionally removed.
For example you can use Ammonite
ammonite.Main(verboseOutput = false).runCode("""println("Hello world!")""")
// Hello world!
build.sbt
lazy val root = project
.in(file("."))
.settings(
name := "scala3demo",
version := "0.1.0-SNAPSHOT",
scalaVersion := "3.1.3",
libraryDependencies ++= Seq(
"com.lihaoyi" % "ammonite" % "2.5.4-22-4a9e6989" cross CrossVersion.full,
),
excludeDependencies ++= Seq(
ExclusionRule("com.lihaoyi", "sourcecode_2.13"),
ExclusionRule("com.lihaoyi", "fansi_2.13"),
),
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.