繁体   English   中英

如何在Scala3运行时编译和执行scala代码?

[英]How to compile and execute scala code at run-time in Scala3?

我想在运行时使用 Scala3 编译和执行 Scala 代码作为字符串。 例如在 Scala 2 中我会使用反射

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!

如果我尝试在 Scala3 中运行此代码,我会得到

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

如何在 Scala3 中翻译此代码?

根据 Odersky 教授的评论,您搜索的功能似乎已被故意删除。

例如,您可以使用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"),
    ),
  )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM