gpt4 book ai didi

scala - 将字符串转换为可运行代码的方法有哪些?

转载 作者:行者123 更新时间:2023-12-01 09:54:32 24 4
gpt4 key购买 nike

我找不到如何将字符串转换为可运行代码,例如:

val i = "new String('Yo')"
// conversion
println(i)

应该打印

Yo

转换后。

我在另一篇文章中找到了以下示例:

import scala.tools.nsc.interpreter.ILoop
import java.io.StringReader
import java.io.StringWriter
import java.io.PrintWriter
import java.io.BufferedReader
import scala.tools.nsc.Settings

object FuncRunner extends App {

val line = "sin(2 * Pi * 400 * t)"

val lines = """import scala.math._
|var t = 1""".stripMargin

val in = new StringReader(lines + "\n" + line + "\nval f = (t: Int) => " + line)
val out = new StringWriter

val settings = new Settings

val looper = new ILoop(new BufferedReader(in), new PrintWriter(out))
val res = looper process settings
Console println s"[$res] $out"
}

链接:How to convert a string from a text input into a function in a Scala

但似乎 scala.tools 不再可用,而且我是 Scala 的新手,所以我不知道如何替换它。现在可能只有其他方法可以做到这一点。

谢谢!

最佳答案

您可以使用 Quasiquotes(实验模块)简单地执行包含在 String 中的代码。

import scala.reflect.runtime.universe._
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox

// TO compile and run code we will use a ToolBox api.
val toolbox = currentMirror.mkToolBox()

// write your code starting with q and put it inside double quotes.
// NOTE : you will have to use triple quotes if you have any double quotes usage in your code.
val code1 = q"""new String("hello")"""
//compile and run your code.
val result1 = toolbox.compile(code1)()

// another example
val code2 = q"""
case class A(name:String,age:Int){
def f = (name,age)
}
val a = new A("Your Name",22)
a.f
"""

val result2 = toolbox.compile(code2)()

REPL 中的输出:

// Exiting paste mode, now interpreting.

import scala.reflect.runtime.universe._
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox
toolbox: scala.tools.reflect.ToolBox[reflect.runtime.universe.type] = scala.tools.reflect.ToolBoxFactory$ToolBoxImpl@69b34f89
code1: reflect.runtime.universe.Tree = new String("hello")
result1: Any = hello
code2: reflect.runtime.universe.Tree =
{
case class A extends scala.Product with scala.Serializable {
<caseaccessor> <paramaccessor> val name: String = _;
<caseaccessor> <paramaccessor> val age: Int = _;
def <init>(name: String, age: Int) = {
super.<init>();
()
};
def f = scala.Tuple2(name, age)
};
val a = new A("Your Name", 22);
a.f
}
result2: Any = (Your Name,22)

scala>

要了解更多关于 Quasiquotes 的信息: http://docs.scala-lang.org/overviews/quasiquotes/setup.html

关于scala - 将字符串转换为可运行代码的方法有哪些?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31054237/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com